In this tutorial, we are going to learn how to convert InputStream to Reader in Java using built-in Java methods and external libraries like
Apache Commons IO.
For more Java I/O related articles, check the following links:
2. Converting InputStream to Reader using
In plain Java converting an
Reader is straightforward:
In this example we can create
Reader instance by wrapping
InputStream inside an
If we know the encoding of byte-base stream, we can specify it in the second parameter of
InputStreamReader constructor, for example:
BufferedReader use the following:
3. Input Stream to Reader with
Guava is an open-source set of common libraries for Java. It comes with nice utility methods for IO operations. The following example shows how to use
CharSource to create
This solution is not so obvious like the plain Java one. First, we have to convert the
InputStream to the
byte array and then use
CharSource.wrap method to create a character-based stream.
4. Convert InputStream to Reader using
Apache Commons IO
Finally, the solution using
Apache Commons IO:
This solution is not straightforward. Just like in program using
Guava library, here we also have to convert InputStream to an array of bytes first. Then, we can create
CharSequenceReader object that wraps
String with given bytes.
CharSequenceReader class is a subclass of a
In this article, we presented several solutions on how to convert
InputStream to a
Reader in Java. The important thing to remember is that InputStream is a
byte-based stream and Readers are
character-based. Following this line of thought, in this article, we illustrated how to convert a byte-based stream to a character-based stream. Notice that since a
InputStream just provides bytes, converting it to text-based stream means the encoding must be known.
All examples used in this tutorial are available under our GitHub.