In this article, we are going to present how to convert Reader to InputString with plain Java, Guava, and Apache Commons IO library. There is no straightforward solution, but let's take a look at several approaches.
In this example, first, we convert Reader to String, then we get byte array from that String and create the ByteArrayInputStream from it.
3. Reader to InputStream using Guava
Using Guava gives us a one-liner solution:
In this example, we used utility class CharStreams that converts Reader to a String. Then, we get bytes from that String and created an instance of ByteArrayInputStream using that byte array.
4. Convert Reader to InputStream using Apache Commons IO library
In Apache Commons IO library we have also dedicated method that can do the conversion in a single line of code:
In this example, we used IOUtils.toByteArray(..) method that returns byte array from given Reader. Then we created ByteArrayInputStream that based on that bytes.
5. Conclusion
In this article, we illustrated several ways to convert Reader to InputStream in Java. There is no straightforward solution to that transformation, so to achieve that we had to first convert Reader to Byte Array and then convert Byte Array to InputStream.
As usual, examples used in this article are available under the GitHub repository.
{{ 'Comments (%count%)' | trans {count:count} }}
{{ 'Comments are closed.' | trans }}