文件读写(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 包),来自 InputStreamReader 的扩展。不需要额外依赖,Kotlin 标准库自带。

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


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

相关推荐
最强小杰11 小时前
gpt-5.6-sol 频繁报 503 怎么办?区分容量熔断和限速 429 的排查方法 + 可复用 retry wrapper
java·人工智能·gpt·ai
夜雪一千13 小时前
MySQL 全局锁是什么?原理、风险、备份踩坑完整实战
android·mysql·adb
吠品13 小时前
Wine 在 Linux 上运行 Windows 软件完整指南
java·linux·服务器
亚历克斯神14 小时前
智能搜索系统的升级复盘——从 Elasticsearch 到混合检索的检索质量提升
java·spring·微服务
金銀銅鐵15 小时前
[Java] 一个方法最多可以有多少个入参?
java·jvm
哭哭啼15 小时前
JAVA服务问题诊断
java·开发语言·jvm
Sayuanni%316 小时前
SpringBoot 从注解到源码:核心知识点总结
java·spring boot·后端
坚定信念,勇往无前16 小时前
Maven 私有仓库-nexus
java
Minner-Scrapy16 小时前
Scrapy 2.17 源码解析:Scheduler 调度器与磁盘/内存双队列
java·爬虫·python·scrapy·网络爬虫·twisted
晚风醉蝶16 小时前
1-11-奇偶排序-OddEvenSort
java·数据结构·算法