English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
In this program, you will learn how to use the Java String initialization program to convert an output stream (OutputStream) to a 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); } }
When the program is run, the output is:
Hello there!
In the above program, we created an OutputStream based on the given string line. This is done using the stream's write() method
Then, we can simply use the String constructor to convert OutputStream to a final String, which accepts a byte array. To do this, we use the stream's toByteArray() method