android:无法写入文件dir,但可以在包dir中 [英] 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");
}
}
如果我改用:
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.
推荐答案
首先,摆脱 printStackTrace()
调用,并将 IOException
对象提供给 android.util.Log
(例如, e()
调用中的第三个参数).
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).
第二,/data/data/APP_PACKAGE/settings.ser
不在您的文件出现在第一个代码清单中.它将进入/data/data/APP_PACKAGE/files/settings.ser
.
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
.
第三,当您的应用安装在SD上时,/data/data/APP_PACKAGE/settings.ser
可能不是Android 2.2上的有效路径.
Third, /data/data/APP_PACKAGE/settings.ser
may not be a valid path on Android 2.2 when your app is installed on SD.
这篇关于android:无法写入文件dir,但可以在包dir中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!