How to convert InputStream to String in Java

In this post we will learn about the different approaches on how to convert InputStream to String in Java. There are a few approaches to achieve the desired result such as using plain Java, Apache Commons IO and Guava.

Convert InputStream to String using BufferedReader:

Below is an example to demonstrate the conversion when using the BufferedReader class in Java 8. Note the lines() method, throws an UncheckedIOException in the case when an error is encountered.

Output:

Convert InputStream to String using IOUtils from ApacheCommons IO:

In addition to the plain Java example you can use the ApacheCommons library IOUtils class to achieve the same result as illustrated below.

Output:

Convert InputStream to String using CharStreams from Guava:

A third option as an alternative to the above examples is to use the  CharStream class from the Guava library.

Output:

In general, to the above examples it is good practice to close any InputStreams you have open so that you don’t leak resources unnecessarily.

In conclusion I hope you found this post useful. I have illustrated a few approaches that allow you to convert an InputStream to String in Java.

Similar posts:

  1. How to convert a Byte Array to String
  2. How to parse a JSON file using GSON

References:

Below I have listed the API documentation so that you can find any additional information you require.

  1. Java InputStream API documentation
  2. Guava CharStreams API documentation
  3. Apache Commons IOUtils API documentation

 

 

 

Leave a Reply

Your email address will not be published. Required fields are marked *