Java program to convert outputstream to string
Here is a Java program to convert an OutputStream
to a String
:
import java.io.ByteArrayOutputStream; import java.io.OutputStream; public class ConvertOutputStreamToString { public static void main(String[] args) { try { // Create an OutputStream OutputStream outputStream = new ByteArrayOutputStream(); // Write some data to the OutputStream String data = "Hello, world!"; outputStream.write(data.getBytes()); // Convert the OutputStream to a String String outputString = outputStream.toString(); // Print the output String System.out.println(outputString); } catch (Exception e) { e.printStackTrace(); } } }
This program first creates an OutputStream
object, outputStream
, and writes some data to it using the OutputStream.write(byte[] b)
method. The data is in the form of a string, which is converted to a byte array using the String.getBytes()
method.
Next, the program converts the OutputStream
to a String
using the OutputStream.toString()
method. This method returns a String
containing the characters that were written to the OutputStream
.
Note that the toString()
method of an OutputStream
returns a string representation of the object, and not the data that was written to the stream. To get the data that was written to the stream, you need to use a ByteArrayOutputStream
instead of a plain OutputStream
. The ByteArrayOutputStream
writes the data to an internal byte array, which can then be converted to a String
using the String(byte[] bytes)
constructor, like this:
import java.io.ByteArrayOutputStream; import java.io.OutputStream; public class ConvertByteArrayOutputStreamToString { public static void main(String[] args) { try { // Create a ByteArrayOutputStream ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); // Write some data to the ByteArrayOutputStream String data = "Hello, world!"; byteArrayOutputStream.write(data.getBytes()); // Convert the ByteArrayOutputStream to a String String outputString = new String(byteArrayOutputStream.toByteArray()); // Print the output String System.out.println(outputString); } catch (Exception e) { e.printStackTrace(); } } }
This program uses a ByteArrayOutputStream
instead of a plain OutputStream
, and converts the internal byte array of the ByteArrayOutputStream
to a String
using the String(byte[] bytes)
constructor.