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

Android Studio无法写入assets目录下.properties文件问题咨询

解决Android中Assets目录文件无法写入的问题

你遇到的问题本质是Android的Assets目录是只读的——这个目录里的文件是打包进APK的,安装后APK文件本身处于只读状态,所以直接写入Assets里的文件必然会抛出FileNotFoundException (Read-only file system)错误。

正确的思路是:先把Assets里的userInfo.properties复制到应用的可写存储目录(比如内部私有存储的files目录),之后所有的读写操作都针对这个复制后的文件。下面是完整的解决方案:

核心步骤

  • 先判断应用内部存储的files目录下是否已存在userInfo.properties,如果不存在,从Assets目录复制过去
  • 后续的加载、修改、保存操作全部基于这个可写路径下的文件

修改后的完整代码

Properties props = new Properties();
String fileName = "userInfo.properties";
// 获取应用内部私有存储的files目录路径
File targetFile = new File(getBaseContext().getFilesDir(), fileName);
InputStream inputStream = null;
OutputStream outputStream = null;

try {
    // 第一步:如果目标文件不存在,从Assets复制模板文件到可写目录
    if (!targetFile.exists()) {
        inputStream = getBaseContext().getAssets().open(fileName);
        outputStream = new FileOutputStream(targetFile);
        // 逐字节复制文件内容
        byte[] buffer = new byte[1024];
        int length;
        while ((length = inputStream.read(buffer)) > 0) {
            outputStream.write(buffer, 0, length);
        }
        // 先关闭复制用的流
        outputStream.close();
        inputStream.close();
    }

    // 第二步:加载可写目录下的属性文件并修改
    inputStream = new FileInputStream(targetFile);
    props.load(inputStream);
    props.put("name", "smith");
    Log.d(TAG, "onCreate: PROPERTIES TEST NAME CHANGE: " + props.getProperty("name"));

    // 第三步:将修改后的属性保存回可写目录
    outputStream = new FileOutputStream(targetFile);
    props.store(outputStream, "Updated user info");

} catch (IOException e) {
    e.printStackTrace();
} finally {
    // 确保所有流都被正确关闭
    try {
        if (inputStream != null) inputStream.close();
        if (outputStream != null) outputStream.close();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

关键细节说明

  • getBaseContext().getFilesDir():获取应用的内部私有存储目录,这个目录只有你的应用能访问,不需要申请额外的存储权限
  • 复制文件的逻辑:第一次运行应用时把Assets里的初始配置文件复制到可写目录,后续直接操作这个本地文件即可
  • 所有读写操作都指向targetFile,彻底避开了Assets目录的只读限制

这样就能完美解决你遇到的写入权限问题,同时保留了从Assets加载初始配置的需求。

内容的提问来源于stack exchange,提问作者G Cox

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.15 03:54:51