## 使用 Kotlin USE 简化文件读写

使用 Kotlin USE 简化文件读写

Use Kotlin USE to shorten file reading

常规写法

常规的文件读写如下;

private val pdfReader by lazy {
    val file = File(cacheDir, fileName)
    val outputStream = FileOutputStream(file)
    try {
       val inputStream = assets.open(fileName)
       var bytesCopied: Long = 0
       val buffer = ByteArray(8 * 1024)
       var bytes = inputStream.read(buffer)
       while (bytes >= 0) {
           outputStream.write(buffer, 0, bytes)
           bytesCopied += bytes
           bytes = inputStream.read(buffer)
       }
    } finally {
       outputStream.close()
    }
    PdfReader(file)
}

使用Use

Kotlin1.2开始,提供一个 use扩展方法,可以用在 Closeable类中
上面代码可以精简成:

private val pdfReader by lazy {
    val file = File(cacheDir, fileName)
    val outputStream = FileOutputStream(file)
    outputStream.use { outputStream ->
        val inputStream = assets.open(fileName)
        var bytesCopied: Long = 0
        val buffer = ByteArray(8 * 1024)
        var bytes = inputStream.read(buffer)
        while (bytes >= 0) {
            outputStream.write(buffer, 0, bytes)
            bytesCopied += bytes
            bytes = inputStream.read(buffer)
        }
    }
    PdfReader(file)
}

福利时间 Copy-to

上面的 流拷贝也会一个扩展。 InputStream.copyTo

private val pdfReader by lazy {
    val file = File(cacheDir, fileName)
    val outputStream = FileOutputStream(file)
    outputStream.use { fileOut ->
        assets.open(fileName).copyTo(fileOut)
    }
    PdfReader(file)
}

福利时间2 outputStream()扩展

File 类 也有一个扩展函数 outputStream()

private val pdfReader by lazy {
    val file = File(cacheDir, fileName)
    file.outputStream().use { fileOut ->
        assets.open(fileName).copyTo(fileOut)
    }
    PdfReader(file)
}

WOW ,改造完成,12行代码,精简成3行。

课外阅读:

InputStream 读取出 字符串 (Text,String)

val myString = inputStream.bufferedReader().use { bufferReader -> 
	bufferReader?.readText() 
}

你可能感兴趣的:(kotlin,android,开发语言)