Google News
logo
Java Program to Convert OutputStream to String
There is no direct way to convert an OutputStream to a String in Java. However, we can write the data to a ByteArrayOutputStream and then convert the byte array to a String. Here's a Java program to do that :
Program :
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.OutputStream;

public class OutputStreamToString {
    public static void main(String[] args) throws IOException {
        String str = "Hello, world!";
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        OutputStreamToString.convertStringToOutputStream(str, outputStream);
        String convertedString = new String(outputStream.toByteArray());
        System.out.println("The output string is: " + convertedString);
    }

    public static void convertStringToOutputStream(String str, OutputStream outputStream) throws IOException {
        outputStream.write(str.getBytes());
    }
}
Output :
The output string is: Hello, world!
In this program, we first create an instance of the ByteArrayOutputStream class. This class implements an output stream in which the data is written into a byte array.

We then call the convertStringToOutputStream method and pass the input string and the ByteArrayOutputStream object as arguments. This method writes the byte representation of the string to the output stream using the write method of the OutputStream class.

Finally, we convert the byte array to a String object using the String constructor that takes a byte array