Java Program to Convert InputStream to String

To understand this example, you should have the knowledge of the following Java programming topics:


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);

    }
}

Output

Hello there!

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

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

Since, the reader can throw IOException, we have the throws IOException in the main function as:

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