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

前端 未结 3 447
小蘑菇
小蘑菇 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条回答
  •  萌比男神i
    2020-12-04 16:42

    Kotlin has a specific extensions just for this purpose.

    The simplest:

    val inputAsString = input.bufferedReader().use { it.readText() }  // defaults to UTF-8
    

    And in this example you could decide between bufferedReader() or just reader(). The call to the function Closeable.use() will automatically close the input at the end of the lambda's execution.

    Further reading:

    If you do this type of thing a lot, you could write this as an extension function:

    fun InputStream.readTextAndClose(charset: Charset = Charsets.UTF_8): String {
        return this.bufferedReader(charset).use { it.readText() }
    }
    

    Which you could then call easily as:

    val inputAsString = input.readTextAndClose()  // defaults to UTF-8
    

    On a side note, all Kotlin extension functions that require knowing the charset already default to UTF-8, so if you require a different encoding you need to adjust the code above in calls to include an encoding for reader(charset) or bufferedReader(charset).

    Warning: You might see examples that are shorter:

    val inputAsString = input.reader().readText() 
    

    But these do not close the stream. Make sure you check the API documentation for all of the IO functions you use to be sure which ones close and which do not. Usually if they include the word use (such as useLines() or use()) thy close the stream after. An exception is that File.readText() differs from Reader.readText() in that the former does not leave anything open and the latter does indeed require an explicit close.

    See also: Kotlin IO related extension functions

提交回复
热议问题