Kotlin专题程序员Kotlin编程

35. 简单的文件读取方法

2017-11-27  本文已影响59人  厚土火焱

读取文件使用 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)
    }
}
上一篇 下一篇

猜你喜欢

热点阅读