Convert Output Stream to String in Java

Exercise:

Write a Java Program to convert Output Stream to String.

Click Here to View the Solution!
import java.io.*;
public class OutputStreamString {
    public static void main(String[] args) throws IOException {
  
         ByteArrayOutputStream stream = new ByteArrayOutputStream();
         String line = "Hello World!";
         stream.write(line.getBytes());
         String finalString = new String(stream.toByteArray());
         System.out.println(finalString);
     }
 } 
Click Here to View the Output!
Hello World!
Click Here to View the Explanation!
  • This program deals with the transformation of an Output Stream into a string by employing ByteArrayOutputStream().
  • First step is to create an instance of ByteArrayOutputStream() by the name of stream, then the provided string Hello World! is stored into variable line.
  • This line is converted into a byte sequence by employing write method on stream instance.
  • This byte sequence is transformed into a modifiable byte array by employing toByteArray().
  • The converted results are stored into a variable finalString and then it is displayed as an output on the console.

%d bloggers like this: