Java IO

Java InputStream to String example

Java InputStream to String example shows how to convert InputStream to String in Java. Example also shows various ways to convert InputStream to String.

How to convert InputStream to String in Java?

There are various ways to convert InputStream to String as given below.

1) Using BufferedReader and InputStreamReader classes

Create BufferedReader from InputStream using InputStreamReader. Read the contents line by line from BufferedReader and append the lines to StringBuilder. Once done, convert StringBuilder to String using toString method.

Example

Output

Note: This approach converts “\r” or “\r\n” new line characters to “\n”.

2) Using ByteArrayOutputStream and InputStream read method

In this approach, we are going to read stream into byte buffer and then write buffer to the ByteArrayOutputStream. Once all the bytes are read from the stream, we will convert it to String using toString method.

Example

3) Using ByteArrayOutputStream and BufferedInputStream classes

This approach is similar to the previous approach with one difference. We are going to use BufferedInputStream instead of reading bytes directory from the InputStream to the byte array buffer.

Example

4) Using Scanner class

This approach uses Scanner class to read from InputStream till end of text by providing “\A” pattern which matches the start of the string.

Example

5) Using Apache Commons IOUtils toString method

It is an absolute breeze to convert input stream to String if you use IOUtils class from Apache Commons library as given below.

It could not be easier than this. Supply input stream and the character set in the arguments and it’s done.

6) Using Apache Commons IOUtils copy method

This approach uses IOUtil’s copy method to write input stream to StringWriter object and then converting the StringWriter to String.

7) Using Java 8 Streams

Finally, If you are using Java 8 or later version, you can use Streams to achieve the same as given below.

Note: This approach converts line breaks to \n.

What is the suggested way to convert InputStream to String?

Approach 1 and 7 converts “\r\n” and “\r” to “\n” which may not be desired in a particular use case. Approach 2, 3 and 5 are suggested as they should run faster as compared to other approaches.

Please let us know your views in the comments section below.

Join 1000+ fellow learners! Enter your email address below: