2014-02-15 119 views
1

文件我有这些方法读取和写入文件:无法读取奇怪的原因

/* Write content to a file */ 
    private void writeToFile(ArrayList<String> list) { 
     File file = new File("jokesBody1.bjk");  
     FileOutputStream fos; 
     if(list != null){ 
     try {   
       file.createNewFile(); 
       fos = openFileOutput("jokesBody1.bjk",Context.MODE_PRIVATE); 
       ObjectOutputStream out = new ObjectOutputStream(fos); 
       out.writeObject(list); 
       out.close(); 
     } catch (FileNotFoundException e) { 
       e.printStackTrace(); 
     } catch (IOException e) { 
       e.printStackTrace(); 
     } 
     }else{ 
      try { 
       file.createNewFile(); 
       fos = openFileOutput("jokesBody1.bjk",Context.MODE_PRIVATE); 
       ObjectOutputStream out = new ObjectOutputStream(fos); 
       out.writeObject(""); 
       out.close(); 
     } catch (FileNotFoundException e) { 
       e.printStackTrace(); 
     } catch (IOException e) { 
       e.printStackTrace(); 
     } 
     } 
    } 

    /* Read file's content */ 
    private ArrayList<String> readFromFile() { 
     File file = new File("jokesBody1.bjk"); 
     ArrayList<String> list = new ArrayList<String>(); 
     try { 
      file.createNewFile(); 
      ObjectInputStream ois = new ObjectInputStream(new FileInputStream(file)); 
      try { 
       list = (ArrayList)ois.readObject(); 
      } catch (ClassNotFoundException e) { 
       e.printStackTrace(); 
      } 
      ois.close(); 
      } catch (IOException e) { 
      Log.e("log activity", "Can not read file: " + e.toString()); 
     } 

     return list; 
    } 

Everyrhing似乎没什么问题,但是当我运行的代码,我发现了以下错误:

02-15 17:02:07.655: E/log activity(1882): Can not read file: java.io.IOException: open failed: EROFS (Read-only file system) 

为什么系统read only?我在创建文件时应该做些什么,如果它不存在file.createNewFile();

我知道我错过了一些非常小的东西,但作为一个初学者,我无法发现它。

+0

当您打算输出文件时,您不需要调用createNewFile(),而您*不应该在您打算输入时调用它,否则您将得到一个空的文件。 – EJP

回答

1

你可能在Linux上得到这个错误。
此文件系统以只读方式进行安装。
所以你不能写信给它。

+0

我在Windows 7上。 – chility

+0

检查权限,此文件所在文件系统的类型,以及该方向上的任何内容。这基本上就是这个错误的含义。可能是因为您使用的帐户没有写入权限或类似的权限。 –

+0

我不知道模拟器在哪里创建应用程序目录。 :( – chility