1. Introduction
In this tutorial, we are going to learn how to convert InputStream to Reader in Java using built-in Java methods and external libraries likeGuava
and Apache Commons IO
.
For more Java I/O related articles, check the following links:
2. Converting InputStream to Reader using plain Java
In plain Java converting an InputStream
to Reader
is straightforward:
In this example we can create Reader
instance by wrapping InputStream
inside an InputStreamReader
object.
If we know the encoding of byte-base stream, we can specify it in the second parameter of InputStreamReader
constructor, for example:
To create BufferedReader
use the following:
3. Input Stream to Reader with Guava
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 Reader
:
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 Reader
.
5. Conclusion
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.
{{ 'Comments (%count%)' | trans {count:count} }}
{{ 'Comments are closed.' | trans }}