将数据保留到内部存储时,文件打开失败

时间:2014-02-19 10:29:38

标签: android performance

我正在尝试将数据保存到我的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&amp;在构造函数中file,并在MyClass的不同函数中访问实例,但似乎我必须在每个函数中初始化它们,然后它才有效。但不确定这背后的原因......如果有人可以向我解释。

2 个答案:

答案 0 :(得分:0)

我不确定这一点,但您可能需要致电

if(!file.exists())    
    file.createNewFile()

打开FileOutputStream之前

答案 1 :(得分:0)

在访问文件之前,检查文件是否存在

 File dir = context.getDir("dataDir", context.MODE_PRIVATE);
 if(! dir.exists()){
     if(dir.mkdir());
 }

File file = new File(dir, "myData");
 if(! file .exists()){
     if(file .mkdir());
 }