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

相关推荐
成都大菠萝7 小时前
Android Car CarProperty 车辆信号链路
android
敲代码的鱼7 小时前
PDF 预览与签名批注写回 支持安卓 iOS 鸿蒙 UTS插件
android·前端·ios
时光足迹9 小时前
uni-app 视频通话实战:康复师与患者视频问诊的 6 个致命 Bug 与解决方案
android·ios·uni-app
像我这样帅的人丶你还9 小时前
Java 后端详解(四):分页与搜索
java·javascript·后端
她的男孩9 小时前
数据权限为什么不能只靠注解?Forge 的 Mapper 层 SQL 改写源码拆解
java·后端·架构
tntxia10 小时前
Mybatis的日志输入
java
亦暖筑序11 小时前
Java 8老系统Browser Agent实战:三层拦截把AI操作后台变成可审计流程
java·后端·设计模式
Coffeeee13 小时前
闲聊几句,Android老哥们,你们多久没做技改需求了
android·程序员·代码规范
萝卜er14 小时前
Fragment 生命周期与状态恢复-《Android深水区(四)》
android
萝卜er14 小时前
Intent 显式、隐式与 PendingIntent-《Android深水区(五)》
android