Java Program to Convert OutputStream to String

In this program, you’ll learn to convert outputstream to a string using String initializer in Java.

Example: Convert OutputStream to String

  1. import*;
  2. public class OutputStreamString {
  3. public static void main(String[] args) throws IOException {
  4. ByteArrayOutputStream stream = new ByteArrayOutputStream();
  5. String line = "Hello there!";
  6. stream.write(line.getBytes());
  7. String finalString = new String(stream.toByteArray());
  8. System.out.println(finalString);
  9. }
  10. }

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.