Kotlin Program to Convert OutputStream to String

Converting an OutputStream to a String is a common requirement in Kotlin when working with input/output operations. This process involves converting the bytes written to an OutputStream into a readable string format. In this article, we will write three different Kotlin Program to Convert OutputStream to String.

1. Using ByteArrayOutputStream and String Constructor

1.1 Example Code:

Kotlin
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)
}

Output:

Kotlin
Hello there!

In this example, we create an OutputStream using ByteArrayOutputStream and write a string line to it using the write() method. Then, we convert the contents of the OutputStream to a string finalString using the String constructor that takes a byte array as input.

2. Using PrintStream and ByteArrayOutputStream

2.1 Example Code:

Kotlin
import java.io.*

fun main(args: Array<String>) {
    val outputStream = ByteArrayOutputStream()
    val printStream = PrintStream(outputStream)
    val line = "Kotlin is awesome!"

    printStream.println(line)
    val finalString = outputStream.toString()

    println(finalString)
}

Output:

Kotlin
Kotlin is awesome!

Here, we utilize a PrintStream along with ByteArrayOutputStream. We write the string line to the PrintStream, which internally writes to the ByteArrayOutputStream. Finally, we convert the contents of the ByteArrayOutputStream to a string using toString().

3. Using CharArrayWriter

3.1 Example Code:

Kotlin
import java.io.*

fun main(args: Array<String>) {
    val writer = CharArrayWriter()
    val line = "Writing to CharArrayWriter"

    writer.write(line)
    val finalString = writer.toString()

    println(finalString)
}

Output:

Kotlin
Writing to CharArrayWriter

In this example, we utilize a CharArrayWriter to write the string line. The contents of the CharArrayWriter are then converted to a string using toString().

Summary and Conclusion

Converting an OutputStream to a String in Kotlin can be achieved using various methods:

  1. Using ByteArrayOutputStream and String constructor for byte array conversion.
  2. Utilizing PrintStream along with ByteArrayOutputStream for text conversion.
  3. Employing CharArrayWriter for character-based output conversion.

Each method offers flexibility and caters to different use cases. Understanding these approaches empowers developers to efficiently handle OutputStream to String conversions in their Kotlin programs, enhancing the versatility and readability of their code.