English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
Java complete list of examples
Dans ce programme, vous apprendrez à utiliser un programme d'initialisation de chaîne de Java pour convertir un flux de sortie (OutputStream) en chaîne de caractères.
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 running the program, 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.write() method
Then, we just need to use the String constructor to convert OutputStream to finalString, which accepts a byte array. For this, we use the stream.toByteArray() method