Convert an Input Stream to String in Java

In this post, we will see how to convert an Input Stream to String in Java using BufferedReader, Scanner class, Guava and Apache Commons IO.

 

1. Using BufferedReader

We can use efficient BufferedReader class to read text from the input character stream by wrapping a BufferedReader around InputStreamReader.

 

Download   Run Code

Output:

Techie
Delight

 

2. Using Scanner

We can also use a Scanner by using the beginning of the input or the end of the input as a delimiters. This is demonstrated below:

 

Download   Run Code

Output:

Techie
Delight

 

3. Using Guava’s Library

Guava’s CharStreams class toString() method reads all characters from a Readable object into a String. So if we can get a Readable object from input stream, we can convert it to stream.

 

Download   Run Code

Output:

Techie
Delight

 

4. Using IOUtils Class from Apache Commons IO

Similar to Guava, Apache Commons IO IOUtils Class toString() method can directly get the contents of an InputStream as a String using the specified character encoding.

 

Download   Run Code

Output:

Techie
Delight

 
One can also use IOUtils.copy() method that copies bytes from an InputStream to chars on a Writer using the specified character encoding.

 

Download   Run Code

Output:

Techie
Delight

 

 
Thanks for reading.




Please use ideone or C++ Shell or any other online compiler link to post code in comments.
Like us? Please spread the word and help us grow. Happy coding 🙂
 





Leave a Reply

Notify of
avatar
wpDiscuz