To read/convert an InputStream into a String in Java, you can use a BufferedReader to read the contents of the input stream line by line, and then append each line to a StringBuilder object to build the complete string. Here's an example code snippet to do this:
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.IOException;
public class InputStreamToStringExample {
public static String convertStreamToString(InputStream inputStream) throws IOException {
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
StringBuilder sb = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
sb.append(line).append("\n");
}
reader.close();
return sb.toString();
}
public static void main(String[] args) throws IOException {
InputStream inputStream = ... // your InputStream object here
String inputString = convertStreamToString(inputStream);
System.out.println(inputString);
}
}
In the above example, the convertStreamToString() method takes an InputStream object as input and returns a String object. The method creates a BufferedReader to read the contents of the input stream line by line. Each line is then appended to a StringBuilder object to build the complete string. Finally, the method returns the string by calling the toString() method on the StringBuilder object.
In the main() method, you can call convertStreamToString() with your own InputStream object, and it will return the contents of the input stream as a String.
Comments (0)