How do I read / convert an InputStream into a String in Java?

 

You can read and convert an InputStream into a String in Java using various approaches. One common way is to use the java.io.BufferedReader class to read the stream line by line and then concatenate the lines into a String. Here's an example:

java
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; public class InputStreamToStringExample { public static String convertInputStreamToString(InputStream inputStream) throws IOException { BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream)); StringBuilder stringBuilder = new StringBuilder(); String line; while ((line = reader.readLine()) != null) { stringBuilder.append(line).append("\n"); } reader.close(); return stringBuilder.toString(); } public static void main(String[] args) throws IOException { // Example InputStream (you can replace this with your actual InputStream) InputStream inputStream = InputStreamToStringExample.class.getResourceAsStream("/example.txt"); String result = convertInputStreamToString(inputStream); System.out.println(result); } }

In this example:

  • The convertInputStreamToString method takes an InputStream as an argument and uses a BufferedReader to read each line from the stream and append it to a StringBuilder.
  • The InputStreamToStringExample class demonstrates how to convert an example InputStream (you can replace it with your own) into a String.
  • Remember to replace "/example.txt" with the path to your actual input stream.

This approach reads the input stream line by line and concatenates the lines using newline characters, effectively converting the stream into a String.

Comments