Roufid

5 ways to convert Inputstream to String in Java

Java

This tutorial shows 5 different ways to convert InputStream to String in Java.  

Used in this tutorial


The tutorial source code is available on Github. Download the source

Native Java

java.io.BufferedReader

The first step to convert an InputStream to String in Java is by using java.io.BufferedReader. Below the Java code :

Try-with-resources is used here to allow the automatic closing of the BufferedReaderIt will only compile with a version equal to or greater than 1.7.  Put the bufferedReader  instantiation inside the try block if you are using a version prior to 1.7.

java.util.Scanner

java.util.Scanner provides a much more easier way to convert an InputStream to String as below :

Java 1.8

Stream API

You can use Collectors of the Java Stream API to make the InputStream to String conversion. Below the code to use :

Third-party libraries

Apache Commons IO

Apache Commons IO provides the utility class org.apache.commons.io.IOUtils to convert an InputStream. You need first to add the dependency to work classpath :

MavenGradle

Below how to use it :

Guava

Google Guava provides also a powerful way to easily convert an inputStream to a String Java object. Download first the dependency

MavenGradle

and use  com.google.common.io.CharStreams as shown below :

Test the code

Below a JUnit code testing the different conversions :


The tutorial source code is available on Github. Download the source

References