2014-02-15 121 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