You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Android序列化对象至文件报错:只读文件系统异常

解决Android中FileOutputStream抛出"只读文件系统"异常的问题

嘿,这个问题我之前也踩过坑!你直接用FileOutputStream("test.obj")会默认尝试把文件写到系统根目录,但Android系统从很早开始就限制了普通应用对根目录的写入权限,所以才会抛出这个异常。下面给你两种靠谱的解决方案:

方案一:使用应用内部私有存储(推荐)

这个目录是系统专门分配给你的应用的私有空间,只有你的应用能访问,而且不需要申请任何权限,安全又省心。修改后的代码如下:

try {
    // 获取应用内部私有文件目录,路径是/data/data/你的应用包名/files/
    File file = new File(getFilesDir(), "test.obj");
    FileOutputStream fos = new FileOutputStream(file);
    ObjectOutputStream out = new ObjectOutputStream(fos);
    out.writeObject(mShareSecurity);
    // 按顺序关闭流,先关ObjectOutputStream再关FileOutputStream
    out.close();
    fos.close();
} catch(Exception e) {
    mesg = e.getMessage();
    ted++;
}

方案二:使用应用外部私有存储(适合需要文件在SD卡的场景)

如果你想把文件存在SD卡上,推荐用应用专属的外部存储目录——这个目录卸载应用时会被自动删除,同样不需要申请权限。代码示例:

try {
    // 获取外部存储上的应用私有目录,路径是/storage/emulated/0/Android/data/你的应用包名/files/
    File externalDir = getExternalFilesDir(null);
    if (externalDir != null) { // 先判断外部存储是否挂载可用
        File file = new File(externalDir, "test.obj");
        FileOutputStream fos = new FileOutputStream(file);
        ObjectOutputStream out = new ObjectOutputStream(fos);
        out.writeObject(mShareSecurity);
        out.close();
        fos.close();
    }
} catch(Exception e) {
    mesg = e.getMessage();
    ted++;
}

额外小提示

  • 千万别再尝试直接写系统根目录或者其他公共目录了,这些区域的权限管控非常严格;
  • 最好使用try-with-resources语法自动管理流的关闭,避免手动关闭的遗漏或顺序错误,比如:
    try (FileOutputStream fos = new FileOutputStream(file);
         ObjectOutputStream out = new ObjectOutputStream(fos)) {
        out.writeObject(mShareSecurity);
    } catch(Exception e) {
        mesg = e.getMessage();
        ted++;
    }
    

内容的提问来源于stack exchange,提问作者Ted pottel

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.29 06:59:26