文件读写(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 老项目迁移系列,持续更新中。

相关推荐
QianhangQianping11 分钟前
撤销重做不是「存快照」:一个可视化编辑器的Operation 设计
java·前端·数据库·typescript·编辑器·前端架构·撤销重做
海绵宝宝转agent17 分钟前
LeetCodehot100题解
java·笔记·学习·算法·leetcode·深度优先
SunnyDays101118 分钟前
Java 操作 Word 脚注和尾注:添加、读取与删除
java·word
SunnyDays101120 分钟前
Java 为 Word 添加页码:隐藏封面页码、从指定页开始编号、奇偶页页码设置等
java·word·页码
Goway_Hui21 分钟前
【KMP for OpenHarmony】Cache4k 0.14.0 鸿蒙适配
华为·kotlin·harmonyos
开源推荐官24 分钟前
多门店 O2O 商城选型复盘:从开发视角对比主流开源系统
java·架构·开源·php
吴名氏.24 分钟前
Java转AI Agent教程(第二周)超时重试与错误分类
java·人工智能·python·分类·ai agent
Android小码家41 分钟前
framework&framework-minus-apex&android.jar的区别
android·python·jar
技术风向解码者1 小时前
安卓跨端选型:为什么优先看 Kuikly
android
科小怪1 小时前
大肥鱼桌宠下载(2026最新版):在安卓桌面上养一条会走会弹会碎碎念的胖鱼
android