In this article we are going to learn how to convert Reader to InputStream using plain Java solution and external libraries like
Apache Commons IO.
If you are looking for more Java I/O related articles, check the following links:
2. Reader to InputStream in
It is inconceivable that there are no methods in plain Java that converts Reader to InputStream directly, even though the opposite classes: InputStreamReader and OutputStreamWriter are included. So, the solution in plain Java will not be straightforward:
In this example, first, we need to read all characters from given
StringReader and aggregate them in
StringBuilder. Then, using
ByteArrayInputStream we create an instance of
InputStream that wraps bytes array taken from
Note that every time we convert character-based stream to byte-based stream we should specify the encoding that defines how you wish to represent your characters as bytes.
3. Convert Reader to InputStream using
Let's take a look at a simpler example using
In this approach, we have to read all characters from
Reader first. Luckily,
Guava comes with dedicated utility
CharStream that we can use for this operation. Then, String is converted to byte array and wrapped by
4. Reader to InputStream using
Apache Commons IO library
Finally, the best solution comes from
Apache Commons IO library:
Apache Commons IO has a dedicated class -
ReaderInputStream for this kind of conversions, so this is a single-line solution.
In this article, we presented several ways to convert Reader to InputStream in Java. It is a shame that Java doesn't have a direct solution for this operation, yet. Luckily other libraries have.
Sample snippets used in this tutorial are available under our GitHub repository.