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 :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());
}
}
The output string is: Hello, world!
ByteArrayOutputStream
class. This class implements an output stream in which the data is written into a byte array.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.String
object using the String
constructor that takes a byte array