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:
InputStream inputStream = ...;
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
StringBuilder sb = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
sb.append(line);
}
String result = sb.toString();
Alternatively, you can use the IOUtils
class from Apache Commons IO to read the entire InputStream into a String:
InputStream inputStream = ...;
String result = IOUtils.toString(inputStream, StandardCharsets.UTF_8);
You can also use the Scanner
class to read the InputStream:
InputStream inputStream = ...;
Scanner scanner = new Scanner(inputStream).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 the java.util.stream.Stream
API, to process the InputStream incrementally, rather than reading the entire InputStream into memory at once.