Skip to content

Java InputStream to String example

Java InputStream to String example shows how to convert InputStream to String in Java. The 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 the 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 the stream into a byte buffer and then write the 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 the BufferedInputStream instead of reading bytes directly from the InputStream to the byte array buffer.

Example

4) Using Scanner class

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

Example

5) Using Apache Commons IOUtils toString method

It is an absolute breeze to convert the input stream to String if you use the IOUtils class from the 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 an input stream to the StringWriter object and then converting the StringWriter to String.

7) Using Java 8 Streams

Finally, If you are using Java 8 or later versions, 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 convert “\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.

This example is a part of Java String tutorial.

Refer to all File examples to learn more.

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

About the author

Leave a Reply

Your email address will not be published.