Android 读写文件 FileNotFoundException 异常

在尝试按照《Android开发艺术探索》中的示例使用Serializable接口时,遇到FileNotFoundException。问题并非权限问题,而是文件系统的读写限制。解决方案包括使用FileOutputStream带File对象的构造方法,并结合Android的getFilesDir()或getExternalFilesDir(null)方法获取可写路径。在模拟器中,可能因缺少外置存储导致错误,此时可能需要新建模拟器。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

转载请注明出处:http://blog.csdn.net/u013258802/article/details/53010157


照着《Android开发艺术探索》一书敲Serializable接口的例子时,遇到 FileNotFoundException 


例子很简单就是往文件里存个User对象:

User user = new User(0, "liang", true);
ObjectOutputStream out = null;
try {
    out = new ObjectOutputStream(new FileOutputStream("test.txt"));
    out.writeObject(user);
    out.close();
} catch (IOException e) {
    e.printStackTrace();
}

这段抛出异常:FileNotFoundException: Caused by: android.system.ErrnoException: open failed: EROFS (Read-only file system)

看起来感觉像缺少权限,不过跟权限没什么关系。


搜到一篇文章:

http://stackoverflow.com/questions/15711098/trying-to-create-a-file-in-android-open-failed-erofs-read-only-file-system


高赞回答说:

Please use the version of the FileOutputStream constructor that takes a File object. Create that File object based off of some location that you can write to, such as:

  • getFilesDir() (called on your Activity or other Context)
  • getExternalFilesDir() (called on your Activity or other Context)

The latter will require WRITE_EXTERNAL_STORAGE as a permission.

就是说建议用FileOutputStream()方法使用File对象作参数的构造方法,用一个路径去创建File对象:

File file = new File(mContext.getFilesDir().getPath() + "test.txt");
out = new ObjectOutputStream(new FileOutputStream(file));


但实际上这里只是单纯的路径错误而已,构造方法可以使用String name或File file作参数,而name是文件路径:

out = new ObjectOutputStream(new FileOutputStream( mContext.getFilesDir() + "test.txt" ));


获取文件或文件路径的写法很多,Android里的getFilesDir()等方法返回的是File对象,不过File对象可以是文件或路径,这里很明显是路径,所以直接与文件名字符串进行拼接就能得到正确路径,也可采用下面的方式:

File file = new File(mContext.getFilesDir(), "test.txt");
当然比较合理的写法是使用getPath()或者对File对象进行检测(isDirectory()):

out = new ObjectOutputStream(new FileOutputStream( mContext.getFilesDir().getPath() + "test.txt" ));
out = new ObjectOutputStream(new FileOutputStream( mContext.getExternalFilesDir(null) + "test.txt" ));


getExternalFilesDir(null)也不需要用到WRITE_EXTERNAL_STORAGE 权限。

但在模拟器上有可能提示:

Failed to ensure /sdcard/Android/data/package/files: java.lang.SecurityException: Invalid mkdirs path: /storage/self/primary/Android/data/package/files

因为没有外置存储卡,有时候模拟器设置里明明有设置,那这时候只能建议新建模拟器试试了。


FileInputStream提示  java.io.FileNotFoundException: test.txt: open failed: ENOENT (No such file or directory) 同理。


另外 FileOutputStream 和 FileInputStream 也可以使用 Context.openFileOutput 和 Context.openFileInpu t获取:

out = new ObjectOutputStream(mContext.openFileOutput("test.txt",MODE_PRIVATE));
这个方法只能使用文件名作参数,文件存放的位置和 getFilesDir() 相同,都在 /data/data/<package>/files 下。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值