Kotlin Program to Convert OutputStream to String

Example: Convert OutputStream to String

import java.io.*

fun main(args: Array<String>) {

    val stream = ByteArrayOutputStream()
    val line = "Hello there!"

    stream.write(line.toByteArray())
    val finalString = String(stream.toByteArray())

    println(finalString)

}

When you run the program, the output will be:

Hello there!

In the above program, we've created an OutputStream based on the given string line. This is done using stream's write() method.

Then, we simply convert the OutputStream to finalString using String's constructor which takes byte array. For this, we use stream's toByteArray() method.

Here's the equivalent Java code: Java program to convert OutputStream to String.

Did you find this article helpful?