Java Program to Convert OutputStream to String

To understand this example, you should have the knowledge of the following Java programming topics:


Example: Convert OutputStream to String

import java.io.*;

public class OutputStreamString {

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

        ByteArrayOutputStream stream = new ByteArrayOutputStream();
        String line = "Hello there!";

        stream.write(line.getBytes());
        String finalString = new String(stream.toByteArray());

        System.out.println(finalString);
    }
}

Output

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.

Did you find this article helpful?

Our premium learning platform, created with over a decade of experience and thousands of feedbacks.

Learn and improve your coding skills like never before.

Try Programiz PRO
  • Interactive Courses
  • Certificates
  • AI Help
  • 2000+ Challenges