1. Introduction
In this article we are going to learn how to convert Reader to InputStream using plain Java solution and external libraries like Guava
and Apache Commons IO
.
If you are looking for more Java I/O related articles, check the following links:
2. Reader to InputStream in plain Java
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 String
.
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 Guava
Let's take a look at a simpler example using Guava
library:
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 ByteArrayInputStream
.
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.
5. Conclusion
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.
{{ 'Comments (%count%)' | trans {count:count} }}
{{ 'Comments are closed.' | trans }}