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

Java Queue (Queue)

Java Map Collection

Java Set Collection

Java Input Output (I/O)

Java Reader/Writer

Java Other Topics

Java program converts InputStream to string

Comprehensive Java Examples

In this program, you will learn how to use InputStreamReader in Java to convert an InputStream to a string.

Example: Convert InputStream to String

import java.io;*;
public class InputStreamString {
    public static void main(String[] args) throws IOException {
        InputStream stream = new ByteArrayInputStream("Hello there!".getBytes());
        StringBuilder sb = new StringBuilder();
        String line;
        BufferedReader br = new BufferedReader(new InputStreamReader(stream));
        while ((line = br.readLine()) != null) {
            sb.append(line);
        }
        br.close();
        System.out.println(sb);
    }
}

When the program is run, the output is:

Hello there!

In the above program, the input stream is created from String and stored in the variable stream. We also need a string builder sb to create a string from the stream.

Then, we create a buffered reader br from InputStreamReader to read lines from the stream. Using a while loop, we read each line and append it to the string builder. Finally, we close the bufferedReader.

Because the reader can throw IOException, we have in the main functionIOException is thrown:

public static void main(String[] args) throws IOException

Comprehensive Java Examples