This post will discuss how to convert an input stream to a string in Java.

There are several ways to convert an input stream to a string in Java, depending on the version of Java we are using and the libraries we have available. Here are some of the most common methods:

1. Using BufferedReader class

This is a low-level approach that reads bytes from the input character stream and decodes them into characters using a specified charset. The idea is to use the efficient BufferedReader class to read text from the InputStream by wrapping a BufferedReader around InputStreamReader. The characters are then appended to a StringBuilder object, which can be converted to a String. Here’s an example of this approach:

Download  Run Code

 
We can also use the Java 8 Stream API to process the input stream. The idea is to can use the lines() method of BufferedReader to read each line from the InputStream as a Stream, and then use the Collectors.joining() method to join them into a single String. Here’s an example of how we can achieve this:

Download  Run Code

2. Using Scanner class

The Scanner class can scan text from various sources, including InputStreams. We can use a delimiter to specify how to split the input into tokens, and then use the next() method to get the next token as a String. The default delimiter is whitespace, but we can change it to any regular expression. We can use the beginning of the input or the end of the input as a delimiter. To illustrate, consider the following example:

Download  Run Code

3. Using Guava Library

Another option is to use the third party libraries that provide utility methods to convert an InputStream to a String, such as Google Guava. The CharStreams class by Guava provides the toString() method that can read all characters from a Readable object and returns them as a String. The idea is to get a Readable object from the input stream, so can convert it to string. We can do so by wrapping an InputStream with an InputStreamReader. Here is the code demonstrating this:

Download Code

4. Using Apache Commons IO

Like Guava, IOUtils class by Apache Commons IO provides the toString() method which can directly get the contents of an InputStream as a string using the specified character encoding. We can also use the IOUtils.copy() method that copies bytes from an InputStream to chars on a Writer using the specified character encoding. These methods offers better performance and error handling than the plain Java methods. Here is an example of using these methods:

Download Code

That’s all about converting an input stream to a string in Java.