【发布时间】:2014-02-19 20:16:05
【问题描述】:
我正在尝试将数据保存到我的 Android 应用的内部存储中。
我的代码是:
File dir = context.getDir("dataDir", context.MODE_PRIVATE);
File file = new File(dir, "myData");
FileOutputStream fos = null;
ObjectOutputStream oos = null;
fos = new FileOutputStream(file); //Exception here
oos = new ObjectOutputStream(fos);
oos.writeObject(MY_DATA);
oos.flush();
...
...
但是我在打开FileOutputStream时遇到了以下异常:
java.io.FileNotFoundExceptoin ..., open failed: ENOENT (No such file or directory)
02-19 12:18:23.006: V/MyApp(21019): at libcore.io.IoBridge.open(IoBridge.java:427)
02-19 12:18:23.006: V/MyApp(21019): at java.io.FileOutputStream.<init>(FileOutputStream.java:88)
02-19 12:18:23.006: V/MyApp(21019): at java.io.FileOutputStream.<init>(FileOutputStream.java:73)
为什么会抛出这个异常?我哪里错了?
======更新(解决方案)=======
在尝试了以下所有答案后,我没有任何运气,但最终,我解决了问题。事情是这样的:
我有一个单独的持久性类:
public MyClass{
private Context context;
private File dir;
private File file;
public MyClass(Context context){
this.context = context;
// I used to initialize dir & file instances here
dir = context.getDir("dataDir", context.MODE_PRIVATE);
file = new File(dir, "myData");
}
public void persistData(){
//Seems I have to initiate dir & file in this function, then it works
dir = context.getDir("dataDir", context.MODE_PRIVATE);
file = new File(dir, "myData");
//I used to have the following code without above 2 lines, which is not working
FileOutputStream fos = null;
ObjectOutputStream oos = null;
fos = new FileOutputStream(file); //Exception here
oos = new ObjectOutputStream(fos);
oos.writeObject(MY_DATA);
oos.flush();
...
...
}
}
我这样做是为了坚持:
MyClass my = new MyClass(context);
my.persistData();
我曾经在构造函数中初始化dir和file,并在MyClass的不同函数中访问实例,但似乎我必须在每个函数中初始化它们,然后它才能工作。但不确定这背后的原因....如果有人可以向我解释一下。
【问题讨论】:
-
我猜你的文件需要像 myData.txt 这样的扩展名
-
你是否添加了这个权限
-
该权限doesn't exist。
-
@Leem.fin 有趣!我能想到的唯一解释是你得到了不同的路径。您可以在构造函数中打印
file.getAbsolutePath()(在初始化file之后),然后在您的persistData()函数中再次打印(在重新初始化file之后)? -
@PaF,我检查了,它们完全相同(在构造函数和持久函数中)
标签: android performance