Appearance
How do I read / convert an InputStream into a String in Java?
There are several ways to read an InputStream and convert it to a String in Java. One way is to use the BufferedReader and InputStreamReader classes to read the InputStream line by line, and use a StringBuilder to construct the final String:
java
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
try (InputStream inputStream = ...;
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, StandardCharsets.UTF_8))) {
StringBuilder sb = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
sb.append(line).append('\n');
}
String result = sb.toString();
}Alternatively, you can use the IOUtils class from Apache Commons IO to read the entire InputStream into a String. Note that newer versions of Commons IO recommend using the overload that explicitly closes the stream:
java
import org.apache.commons.io.IOUtils;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
try (InputStream inputStream = ...) {
String result = IOUtils.toString(inputStream, StandardCharsets.UTF_8, true);
}You can also use the Scanner class to read the InputStream:
java
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.util.Scanner;
try (InputStream inputStream = ...;
Scanner scanner = new Scanner(inputStream, StandardCharsets.UTF_8)) {
scanner.useDelimiter("\\A");
String result = scanner.hasNext() ? scanner.next() : "";
}It's important to note that these solutions will work for small inputs, but may not be efficient for large inputs. In that case, it may be better to use a streaming solution, such as BufferedReader.lines(), to process the InputStream incrementally rather than reading the entire stream into memory at once:
java
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
import java.util.stream.Collectors;
try (InputStream inputStream = ...;
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, StandardCharsets.UTF_8))) {
String result = reader.lines().collect(Collectors.joining("\n"));
}