为什么我无法读取只读文件?

我有这个方法应该读取一个文件:

/* Read file's content */ private ArrayList readFromFile() { File file = new File("jokesBody1.bjk"); ArrayList list = new ArrayList(); 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; } 

当我调用它时,它返回:

 02-16 06:15:32.686: E/log activity(1380): Can not read file: java.io.IOException: open failed: EROFS (Read-only file system) 

甚至,如果文件是只读的,为什么我看不懂呢? 我真的无法理解什么是wroong。 我的清单中有这个暂停:

有人能给我一个线索吗? 我知道我错过了一些小东西,但我真的无法发现它。

这是我写文件的方式:

 /* Write content to a file */ private void writeToFile(ArrayList list, Context cont) { File file = new File("jokesBody1.bjk"); FileOutputStream fos; if(list != null){ try { fos = cont.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(); } } } 

您正在尝试创建该文件,当然,该文件在只读文件上失败。

删除此行:

 file.createNewFile(); 

这通常用于在写入之前创建新的空文件。 如果您只想读取已存在的文件,那么您真的不需要它。

编辑:

只需使用:

 ObjectInputStream ois = new ObjectInputStream( context.openFileInput("jokesBody1.bjk")); 

当然,您还必须将Context传递给该函数。

您只能使用带完整路径的File 。 要访问私有文件,请使用Context,就像保存文件一样。

您的全部function应如下所示:

 private ArrayList readFromFile(Context context) { ArrayList list = new ArrayList(); try { ObjectInputStream ois = new ObjectInputStream( context.openFileInput("jokesBody1.bjk")); 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; } 

您没有指定任何路径:

 File file = new File("jokesBody1.bjk"); 

所以,你不是说应用程序在哪里查找文件。

也许,你想在这里搜索一下?

 Environment.getExternalStorageDirectory()