Search code examples
javaandroidiosobjective-cwritetofile

Equivalent for NSString writeToFile and archiveRootObject in Android ?


On iOS I use these lines of code to store a large String (JSon)... How can I do the same on Android? What is a file place to put that string? Thanks

NSArray *paths = NSSearchPathForDirectoriesInDomains
(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];


//make a file name to write the data to using the
//documents directory:
NSString *fullFileName = [NSString stringWithFormat:@"%@/subscriptions", documentsDirectory];
[dataReply writeToFile:fullFileName atomically:NO];

And for save directly the array? Like this?

   fullFileName = [NSString stringWithFormat:@"%@/specialElements", documentsDirectory];
  [NSKeyedArchiver archiveRootObject:specialElements toFile:fullFileName];

specialElements is a NSMutableArray


Solution

  • try
    {
        String path = "/data/data/"+getPackageName()+"/test.json";
        File file = getFileStreamPath(path); 
        if (!file.exists())
        {
          file.createNewFile();
        }
    
        FileOutputStream writer = openFileOutput(file.getName(), Context.MODE_PRIVATE);
        writer.write(data.getBytes());//data is your json in String
        writer.flush();
        writer.close();
    }
    catch(Exception e)
    {
        //exception
    }
    

    Along with the below permission in manifest file :

    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />