文件读写(Java IO)→ Kotlin 扩展函数

文件读写(Java IO)→ Kotlin 扩展函数

老写法(Java)

java 复制代码
// 写入文件
FileOutputStream fos = null;
try {
    fos = context.openFileOutput("data.txt", Context.MODE_PRIVATE);
    fos.write("hello world".getBytes());
} catch (IOException e) {
    e.printStackTrace();
} finally {
    if (fos != null) {
        try {
            fos.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

// 读取文件
FileInputStream fis = null;
BufferedReader reader = null;
StringBuilder sb = new StringBuilder();
try {
    fis = context.openFileInput("data.txt");
    reader = new BufferedReader(new InputStreamReader(fis));
    String line;
    while ((line = reader.readLine()) != null) {
        sb.append(line);
    }
} catch (IOException e) {
    e.printStackTrace();
} finally {
    try { if (reader != null) reader.close(); } catch (IOException ignored) {}
    try { if (fis != null) fis.close(); } catch (IOException ignored) {}
}
String content = sb.toString();

问题在哪里

try-catch-finally 嵌套层层叠叠,实际有用的就两行读写代码,其余全是样板。每次忘记 close 就有泄漏风险,IDE 不一定能检查出来。

新写法(Kotlin)

kotlin 复制代码
// 写入
context.openFileOutput("data.txt", Context.MODE_PRIVATE).use { stream ->
    stream.write("hello world".toByteArray())
}

// 读取
val content = context.openFileInput("data.txt").use { stream ->
    stream.bufferedReader().readText()
}

// 逐行读取
val lines = context.openFileInput("data.txt").use { stream ->
    stream.bufferedReader().readLines()
}

// 写入扩展函数 --- 项目中可以抽成工具方法
fun Context.writeToFile(filename: String, content: String) {
    openFileOutput(filename, Context.MODE_PRIVATE).use {
        it.write(content.toByteArray())
    }
}

fun Context.readFromFile(filename: String): String {
    return openFileInput(filename).use {
        it.bufferedReader().readText()
    }
}

一句话注意

Kotlin 的 .use {} 对应 Java 的 try-with-resources,Closeable 接口的实现类都可以用,lambda 结束后自动调用 close(),不会忘。

bufferedReader() 和 readText() 都是 Kotlin 标准库扩展函数(kotlin.io 包),来自 InputStream 和 Reader 的扩展。不需要额外依赖,Kotlin 标准库自带。

toByteArray() 默认用系统默认字符集(通常是 UTF-8)。如果文件是其他编码,用 toByteArray(Charsets.ISO_8859_1) 之类指定编码。


Java Android 老项目迁移系列,持续更新中。

相关推荐
Forget the Dream2 小时前
Spring AI 2.0 系列(二):第一个 ChatClient——从注入到一次完整调用
java·人工智能·spring boot·ai·springai
黑十3 小时前
FDE 怎么快速搭一个可演示页面?最小前端方案
java·大数据·前端·数据库·人工智能
神明不懂浪漫4 小时前
【第八章】多线程(一)
java·开发语言·经验分享·笔记
用户54817845909504 小时前
Java 与 Python 在大模型与智能体领域的选型
java·python
文丑颜不良啊4 小时前
LeetCode3341~3360题目解析
java·leetcode
hai_android4 小时前
一行 asLiveData,背后是一座生命周期的桥
android·java·kotlin
用户9338104348454 小时前
MyBatis-Plus LambdaQueryWrapper 隐式转换踩坑:不知不觉索引失效
java
用户3721574261355 小时前
Java 在 PDF 中查找关键词:获取页码和坐标,并高亮匹配结果
java
Forget the Dream5 小时前
Spring AI 2.0 系列(三):ChatClient 与 ChatModel:Spring AI 2.0 的两层职责
java·人工智能·spring·springai
阿杰m5 小时前
Android源码第二十三章:Telephony、RIL 与 IMS——来电怎么到应用?
android