开发者

android: can't write to files dir but can in package dir

I'm trying to save an object in a file but the file doesn't appear on the device and I don't get an exception either.

public static void save(Context ctx) {
    Log.i("App serialization", "Saving to settings.ser: " + ctx.getFileStreamPath("settings.ser"));
    FileOutputStream fos = null;
    ObjectOutputStream out = null;
    try {
        fos = ctx.openFileOutput("settings.ser", Context.MODE_PRIVATE);
        out = new ObjectOutputStream(fos);
        out.writeObject(ApplicationData.settings);
        out.flush();
        out.close();
        //fos.close();
        Log.i("App serialization", "Finished writing to settings.ser");
    }
    catch(IOException ex) {
        ex.printStackTrace();
        Log.e("App serialization", "Could not save to settings.ser");开发者_运维技巧
    }
}

If instead I use:

try {
        fos = new FileOutputStream("/data/data/APP_PACKAGE/settings.ser");
        out = new ObjectOutputStream(fos);

It works and I can see that the file has been created on the device.

But this isn't cool and it's not the way to do it because the directory structure may change in the future.


First, get rid of the printStackTrace() call, and supply your IOException object to android.util.Log instead (e.g., third parameter in your e() call).

Second, /data/data/APP_PACKAGE/settings.ser is not where your file will wind up in your first code listing. It will go into /data/data/APP_PACKAGE/files/settings.ser.

Third, /data/data/APP_PACKAGE/settings.ser may not be a valid path on Android 2.2 when your app is installed on SD.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜