Android中的NSString writeToFile和archiveRootObject等效吗?

时间:2013-08-21 14:14:00

标签: java android ios objective-c writetofile

在iOS上我使用这些代码行来存储一个大字符串(JSon)......我怎么能在Android上做同样的事情?放置该字符串的文件位置是什么? 感谢

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];

直接保存数组?喜欢这个?

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

specialElements是一个NSMutableArray

1 个答案:

答案 0 :(得分:1)

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
}

以及清单文件中的以下权限:

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