English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Java Basic Tutorial

Java flow control

Java Array

Java Object-Oriented (I)

Java Object-Oriented (II)

Java Object-Oriented (III)

Java Exception Handling

Java List (List)

Java Queue (Queue)

Java Map Collection

Java Set Collection

Java Input Output (I/O)

Java Reader/Writer

Java other topics

Java program converts OutputStream to string

Comprehensive Java Examples

In this program, you will learn how to use the Java String initialization program to convert an output stream (OutputStream) to a string.

Example: Convert OutputStream to 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

Comprehensive Java Examples