Kotlin写入应用内部存储失败:EROFS只读文件系统错误求助
Android Kotlin 内部存储文件写入失败(EROFS错误)解决方案
错误根源
直接使用File("text.def")会默认指向系统根目录,Android系统对该目录有严格的只读限制,因此抛出EROFS (Read-only file system)错误。应用的内部存储必须使用专属的私有目录路径。
正确实现方式
方式1:使用context.filesDir构建文件路径
filesDir是Android提供的应用内部存储私有目录,路径为/data/data/[包名]/files/,应用拥有完全读写权限。
val defFileName = "text.def" // 获取应用内部存储的files目录 val filesDir = context.filesDir // 构建完整的文件对象 val ioFile = File(filesDir, defFileName) try { // writeText会自动处理文件创建、流写入与关闭 ioFile.writeText("Hello World") } catch (e: IOException) { e.printStackTrace() }
方式2:修复openFileOutput代码(解决未生效问题)
你之前的代码未生效,大概率是因为未关闭输出流导致数据未刷入磁盘。使用use语法可自动管理资源:
val ioDefFile = "text.def" try { context.openFileOutput(ioDefFile, Context.MODE_PRIVATE).use { outputStream -> outputStream.write("just a textString".toByteArray()) // use语法会自动关闭流,无需手动调用close() } } catch (e: Exception) { e.printStackTrace() }
openFileOutput默认将文件写入filesDir目录,无需手动指定路径。
方式3:使用FileWriter结合内部存储路径
必须指定应用内部存储的完整路径,不能直接用文件名:
val defFileName = "text.def" val filesDir = context.filesDir val ioFile = File(filesDir, defFileName) try { FileWriter(ioFile).use { writer -> for (x in 0 until DSSize) { writer.write("${dl[x]}\n") } // use自动关闭writer,确保数据写入磁盘 } } catch (exception: Exception) { println(exception.message) }
验证文件是否写入成功
可通过Android Studio的Device File Explorer查看文件,路径为:/data/data/[你的应用包名]/files/text.def
内容的提问来源于stack exchange,提问作者VFarkas2023
相关产品推荐
相关产品推荐

