[英]Why I can't read a read only file?
我有这种方法应该读取文件:
/* 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;
}
当我调用它时,它返回:
02-16 06:15:32.686: E/log activity(1380): Can not read file: java.io.IOException: open failed: EROFS (Read-only file system)
即使文件是只读的,为什么我也看不到它? 我真的不明白什么是错误的。 我的清单上有这样的要求:
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
有人可以给我一个提示吗? 我知道我缺少一些小东西,但我真的找不到它。
这是我写文件的方式:
/* Write content to a file */
private void writeToFile(ArrayList<String> 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,就像保存文件时一样。
您的完整功能应如下所示:
private ArrayList<String> readFromFile(Context context) {
ArrayList<String> list = new ArrayList<String>();
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()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.