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