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

Android应用读取内部存储自定义目录文件时崩溃求助

问题分析与解决方案

问题根源

你用openFileOutput("note.txt", Context.MODE_PRIVATE)保存文件时,这个方法默认会把文件写到filesDir根目录下,而不是你创建的notes子目录。但读取的时候你去notes/note.txt找文件,这个文件根本不存在,所以调用note.readText()会触发文件找不到的异常,导致应用崩溃。

修复步骤

  1. 确保目录创建成功:把noteDirectory.mkdir()改成noteDirectory.mkdirs(),虽然这里父目录filesDir肯定存在,但mkdirs()能确保多级目录都被创建,更稳妥。
  2. 修改保存逻辑:直接操作你定义的note文件对象,替换原来的openFileOutput方式,这样文件会被写到notes子目录下。

修改后的完整代码

// 存储笔记的目录
val noteDirectory = File(applicationContext.filesDir, "notes")
noteDirectory.mkdirs() // 改用mkdirs()确保目录创建

// 存储笔记的文件
val note = File(noteDirectory, "note.txt")

// 文本框内容状态
var createNoteTextValue by remember { mutableStateOf("") }
// 显示内容状态
var displayNoteTextValue by remember { mutableStateOf("") }

// 保存笔记函数
fun saveValue() {
    // 直接写入指定的note文件
    note.writeText(createNoteTextValue)
}

// UI布局
Column(
    horizontalAlignment = Alignment.CenterHorizontally,
    verticalArrangement = Arrangement.Center,
    modifier = Modifier
        .fillMaxSize()
) {
    TextField(value = createNoteTextValue, onValueChange = { createNoteTextValue = it })
    Button(onClick = { saveValue() }) {
        Text(text = "Save")
    }
    Button(onClick = { 
        // 读取前加判断,避免文件不存在时崩溃
        if (note.exists()) {
            displayNoteTextValue = note.readText() 
        } else {
            displayNoteTextValue = "文件不存在"
        }
    }) {
        Text(text = "Show")
    }
    Text(text = displayNoteTextValue)
}

额外优化建议

在读取文件前增加note.exists()判断,这样即使文件没被创建,也不会直接崩溃,而是给用户友好提示。

内容的提问来源于stack exchange,提问作者Bob Rasner

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.21 05:26:00