Java Program to Convert InputStream to String

In this program, you’ll learn to convert input stream to a string using InputStreamReader in Java.

Example: Convert InputStream to String

  1. import*;
  2. public class InputStreamString {
  3. public static void main(String[] args) throws IOException {
  4. InputStream stream = new ByteArrayInputStream("Hello there!".getBytes());
  5. StringBuilder sb = new StringBuilder();
  6. String line;
  7. BufferedReader br = new BufferedReader(new InputStreamReader(stream));
  8. while ((line = br.readLine()) != null) {
  9. sb.append(line);
  10. }
  11. br.close();
  12. System.out.println(sb);
  13. }
  14. }

When you run the program the output will be:

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