English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Kotlin Program Converts InputStream to String (String)

Kotlin Comprehensive Examples

In this program, you will learn to use InputStreamReader in Kotlin to convert an InputStream to a string.

Example: Convert InputStream to String

import java.io.*
fun main(args: Array<String>) {
    val stream = ByteArrayInputStream("Hello there!".toByteArray())
    val sb = StringBuilder()
    var line: String?
    val br = BufferedReader(InputStreamReader(stream))
    line = br.readLine()
    while (line != null) {
        sb.append(line)
        line = br.readLine()
    }
    br.close()
    println(sb)
}

When running the program, the output is:

Hello there!

In the above program, the input stream is created from String and stored in the variable stream. We also need a string builder sb to create a string from the stream.

Then, we create a buffered reader br from InputStreamReader to read lines from the stream. Using a while loop, we read each line and append it to the string builder. Finally, we close the BufferedReader.

Because the reader can throw IOException, we set IOException to be thrown in the main function.

public static void main(String[] args) throws IOException

This is the equivalent Java code:Java Program to Convert InputStream to String.

Kotlin Comprehensive Examples