读取文件使用 BufferedReader(FileReader("abc.txt")) 方法。
先写一个传统的
try {
val br = BufferedReader(FileReader("hello.txt"))
with(br){
var line:String?
while (true){
line = readLine()?:break
println(line)
}
close()
}
} catch (e: Exception) {
println(e.message)
}
kotlin 有自己的特点,可以更少的代码实现这个。
try {
BufferedReader(FileReader("hello.txt")).use {
var line:String?
while (true){
line = it.readLine()?:break
println(line)
}
}
} catch (e: Exception) {
println(e.message)
}
以上两段代码实现的功能是一样的。而第二段代码使用了 use,它可以省去自己写 close 的代码。
顺便欣赏一下 use 的实现吧。
@InlineOnly
public inline fun <T : Closeable?, R> T.use(block: (T) -> R): R {
var closed = false
try {
return block(this)
} catch (e: Exception) {
closed = true
try {
this?.close()
} catch (closeException: Exception) {
}
throw e
} finally {
if (!closed) {
this?.close()
}
}
}
完整代码
package com.cofox.kotlin.mydo.HeighterCodeFunction
import java.io.BufferedReader
import java.io.FileReader
/**
* chapter01
* @Author: Jian Junbo
* @Email: junbojian@qq.com
* @Create: 2017/11/27 0:30
* Copyright (c) 2017 Jian Junbo All rights reserved.
*
* Description: 读取文件
*/
fun main(args: Array<String>) {
/*try {
val br = BufferedReader(FileReader("hello.txt"))
with(br){
var line:String?
while (true){
line = readLine()?:break
println(line)
}
close()
}
} catch (e: Exception) {
println(e.message)
}*/
try {
BufferedReader(FileReader("hello.txt")).use {
var line:String?
while (true){
line = it.readLine()?:break
println(line)
}
}
} catch (e: Exception) {
println(e.message)
}
}