1. Introduction
In this article, we will showcase several ways how to convert Byte Array to Reader using plain Java, Guava
, and Apache Commons IO
library.
Check the following links for other useful articles:
2. Convert Byte Array to Reader using plain Java
Pure Java gives us an almost straightforward solution. We can use StringReader
or InputStreamReader
:
Let's take a look at a solution using StringReader
:
In this example first, we created String
from the given bytes. Then, we create an instance of StringReader
that takes a byte array as a parameter.
In the next approach in pure Java we will use InputStreamReader
:
In this example, we make use of ByteArrayInputStream
to create a byte-based stream, and then, with InputStreamReader
we created an instance of the Reader
.
3. Byte Array to Reader with Guava
library
The next solution will use Guava
library. Let's take a look:
In this example, we need to convert bytes to the String
first because Guava's ByteSource
does not allow direct conversions. Then, we used CharSource
to wrap the String and create Reader
out of it.
4. Byte Array to Reader conversion using Apache Commons IO
Another library we can use to convert Byte Array to Reader is Apache Commons IO
that comes with many helpful utility methods:
In this example, we also need to create String
from given bytes and then use CharSequenceReader
to create a Reader
object.
5. Conclusion
In this article, we showed ways to convert byte[]
to Reader
in Java. The approach using InputStreamReader
is a direct solution, that does not require the intermediary String representation.
Example snippets presented in this article are available in our GitHub repository.
{{ 'Comments (%count%)' | trans {count:count} }}
{{ 'Comments are closed.' | trans }}