【问题标题】:file open failed when persist data to internal storage将数据持久保存到内部存储时文件打开失败
【发布时间】: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();

我曾经在构造函数中初始化dirfile,并在MyClass的不同函数中访问实例,但似乎我必须在每个函数中初始化它们,然后它才能工作。但不确定这背后的原因....如果有人可以向我解释一下。

【问题讨论】:

  • 我猜你的文件需要像 myData.txt 这样的扩展名
  • 你是否添加了这个权限
  • 该权限doesn't exist
  • @Leem.fin 有趣!我能想到的唯一解释是你得到了不同的路径。您可以在构造函数中打印file.getAbsolutePath()(在初始化file 之后),然后在您的persistData() 函数中再次打印(在重新初始化file 之后)?
  • @PaF,我检查了,它们完全相同(在构造函数和持久函数中)

标签: android performance


【解决方案1】:

对此我不确定,但您可能需要致电

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

在打开 FileOutputStream 之前

【讨论】:

  • 我试过你的建议,我得到“IOException: open failed: ENOENT”,它抱怨 java.io.File.createNewFile()
【解决方案2】:

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

 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());
 }

【讨论】:

    猜你喜欢
    • 2017-07-12
    • 1970-01-01
    • 2012-05-16
    • 1970-01-01
    • 2012-07-08
    • 1970-01-01
    • 2011-04-13
    • 2021-06-24
    • 2023-03-10
    相关资源
    最近更新 更多