In this tutorial, we are going to learn how to convert an InputStream to a String in Java using plain Java, Guava, and Apache Commons IO library. Converting operations are very common requirements in many Java applications that process external resources from the filesystem or web.
For more Java I/O related articles, check the following links:
Note that there is a seperate library version for JRE and Android. The Android version of Guava is optimized for use on Android.
In the following example used ByteSource functionality from the Guava library:
In this example we view the ByteSource with our InputStream as a CharSource with UTF8 charset and the use read() method to read it as a String.
Luckily there is an easies way to do the conversion using Guava's CharStreams:
In this example, we used try-with-resources syntax to automatically close the stream but Guava gives us some other great utility class that could be used to close streams:
5. Converting InputStream to String with Apache Commons IO
Conversion from the InputStream to String can be also achieved using Apache Commons IO library. Let's start by adding a dependency to our project. The latest version of the library can be found under the following link: commons-io:commons-io
There are two approaches when using the Apache Commons IO library:
we can use IOUtils.copy() method or,
The following example shows how to use IOUtils.copy method:
The next example presents IOUtils.toString - a method, that allows us to convert InputStream into String in one line:
Keep in mind that neither copy nor toString methods from Apache Commons IO closes the stream, so you have to do it 'manually'.
6. Java InputStream to String using Scanner
To convert an InputStream to a String we can also use Scanner class that comes with java.util package. Scanner iterates over tokens in a stream and by separating tokens using The beginning of the input - (A) we will get the whole content of the stream.
Closing the scanner scanner.close() automatically closing the stream. We could also use try-with-resources that will close scanner implicitly:
7. Converting InputStream to String using java.nio.Files class
Another way to get the content of the InputStream and put it into a String is to use Files class that is available under the new Java NIO API:
In this solution first, we need to create a temporary file and copy there the content from the InputStream. Then, we could use Files.readAllBytes method to read the content of the file and put it into a String.
8. InputStream to String conversion using Java 9 InputStream.readAllBytes() method
Since Java 9 we can readAllByte straight from the InputStream using readAllBytes method:
In this article, we presented approaches to convert InputStream to a String in Java. You should choose the best solution that suits you and will not generate any unnecessary conflicts in your project.