How to convert inputstream to string in java / Various ways of converting inputstream to string in java

java.io.InputStream represents a stream of bytes. Often when reading binary files or from a network, data is returned in an input stream format and we need to read that data and convert it to a string format so that it becomes meaningful.
This post will list out various methods in which the content of an input stream can be converted to a java.lang.String. All the methods assume that you have a source input stream available.

Method 1: Using Scanner class
java.io.Scanner class has a constructor which takes a java.io.Inputstream as argument. Once an object of scanner is created, use its hasNext and next methods to read content of input stream.

Scanner scanner = new Scanner(inputStream);
scanner.useDelimiter("\n");
String content = scanner.hasNext() ? scanner.next():"";
scanner.close();

Note that you need to tell the scanner object about the line separator on which it should divide the tokens read from the input stream. This is done using useDelimiter method with a new line character as argument so that each line is considered as a separate token.
Method 2: Using stream in java 8
Stream is a new concept introduced in java 8 which can be used to read contents from a buffered reader. Thus, in order to get a stream you first need to gain access to a java.io.BufferedReader object.
A buffered reader object can be obtained using its constructor which takes an object of java.io.InputStreamReader as argument.
Now, object of java.io.InputStreamReader can be created using its constructor which takes an input stream as argument. Thus, starting from an input stream, we now have an object of buffered reader.
Once you get a buffered reader object, call its lines method. This method will return an object of java.util.stream.Stream.
This stream can be converted to a string by invoking its collect method accepting a java.util.stream.Collectors object as argument.
Converting this discussion step by step to code, it becomes.

// create an object of inputstreamreader
InputStreamReader reader = new InputStreamReader(inputStream);
// create an object of bufferedreader
BufferedReader br = new BufferedReader(reader);
// get stream object
Stream stream = br.lines();
// convert stream to a string
String content = (String) stream.collect(Collectors.joining("\n"));

Note that joining method of java.util.stream.Collectors method joins the contents of the stream with the supplied separator. In this case, the separator is a new line character(\n).

Above code can be converted to a one-liner as below.

String content = new BufferedReader(new InputStreamReader(inputStream)).
lines().collect(Collectors.joining("\n"));

Method 3: Using InputStreamReader and StringBuilder
java.io.InputStreamReader has a constructor which takes an input stream as argument. It has a read method that reads characters from the underlying input stream into an array.
This array is appended to a java.lang.StringBuilder. Note that read method returns -1 when the stream is read completely and there is not data left. Example,

// create inputstreamreader
InputStreamReader reader = new InputStreamReader(inputStream);
// initialize array to hold stream data
char[] buffer = new char[1024];
StringBuilder contentBuffer = new StringBuilder();
// read stream data into buffer till stream is empty
while(reader.read(buffer, 0, buffer.length)!=-1) {
   // add data read from stream to stringbuffer    
   contentBuffer.append(buffer, 0, buffer.length);
}
// close inputstreamreader
reader.close();
// convert to a string
String content = contentBuffer.toString();
You can also use a java.lang.StringBuffer in place of java.lang.StringBuilder to hold the stream contents.

Method 4: Using IOUtils from Apache Commons
Apache Commons library has a class org.apache.commons.io.IOUtils which has a toString method accepting a java.io.InputStream as argument and returns a string populated with the contents of the supplied input stream.

String contents = IOUtils.toString(inputStream);

Method 5: Using IOUtils from Apache Commons
org.apache.commons..io.IOUtils from Apache Commons library has a copy method which takes two arguments: a java.io.InputStream and a java.io.Writer and copies the contents of the input stream to the writer.
Since we need to convert the input stream to a string, create an instance of a java.io.StringWriter since it is a child class of java.io.Writer and pass it to the copy method. Example,

// create instance of StringWriter
Writer writer = new StringWriter();
// copy input stream to the writer
IOUtils.copy(inputStream, writer);
// convert writer to a string
String contents = writer.toString();

To add Apache Commons library to your project, place following dependencies as per the build tool.

<!- – Maven – ->
<dependency>
   <groupId>commons-io</groupId>
   <artifactId>commons-io</artifactId>
   <version>2.6</version>
</dependency>

<!- – Gradle – ->
compile group: ‘commons-io’, name: ‘commons-io’, version: ‘2.6’

Method 6:  Using CharStreams in guava
Guava library has a com.google.common.io.CharStreams class having a toString method which can be provided a java.io.InputStream as argument and returns a string with the contents of the input stream. Example,

String content = CharStreams.toString(new InputStreamReader(inputStream));

toString method internally takes a java.lang.Readable which is an interface implemented by java.io.InputStream, hence it can be passed to this method.
Guava library can be added to you project using below dependencies.

<!- – Maven – ->
<dependency>
   <groupId>com.google.guava</groupId>
   <artifactId>guava</artifactId>
   <version>27.1-jre</version>
</dependency>

<!- – Gradle – ->
compile group: ‘com.google.guava’, name: ‘guava’, version: ‘27.1-jre’

Hope this post taught you some new ways to convert an input stream to a string in java. Keep visiting!!!

Leave a Reply