In Kotlin, how do I read the entire contents of an InputStream into a String?

前端 未结 3 454
小蘑菇
小蘑菇 2020-12-04 16:19

I recently saw code for reading entire contents of an InputStream into a String in Kotlin, such as:

// input is of type InputStream
val baos =         


        
3条回答
  •  一个人的身影
    2020-12-04 16:32

    Method 1 | Manually Close Stream

    private fun getFileText(uri: Uri):String {
        val inputStream = contentResolver.openInputStream(uri)!!
    
        val bytes = inputStream.readBytes()        //see below
    
        val text = String(bytes, StandardCharsets.UTF_8)    //specify charset
    
        inputStream.close()
    
        return text
    }
    
    • inputStream.readBytes() requires manually close the stream: https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.io/java.io.-input-stream/read-bytes.html

    Method 2 | Automatically Close Stream

    private fun getFileText(uri: Uri): String {
        return contentResolver.openInputStream(uri)!!.bufferedReader().use {it.readText() }
    }
    
    • You can specify the charset inside bufferedReader(), default is UTF-8: https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.io/java.io.-input-stream/buffered-reader.html

    • bufferedReader() is an upgrade version of reader(), it is more versatile: How exactly does bufferedReader() work in Kotlin?

    • use() can automatically close the stream when the block is done: https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.io/use.html

提交回复
热议问题