In this quick tutorial, we’re going to convert a simple byte array to a Reader using plain Java, Guava and finally the Apache Commons IO library.
This article is part of the “Java – Back to Basic” series here on Baeldung.
1. With Plain Java
Let’s start with the simple Java example, doing the conversion via an intermediary String:
@Test
public void givenUsingPlainJava_whenConvertingByteArrayIntoReader_thenCorrect()
throws IOException {
byte[] initialArray = "With Java".getBytes();
Reader targetReader = new StringReader(new String(initialArray));
targetReader.close();
}
An alternative approach would be to make use of an InputStreamReader and a ByteArrayInputStream:
@Test
public void givenUsingPlainJava2_whenConvertingByteArrayIntoReader_thenCorrect()
throws IOException {
byte[] initialArray = "Hello world!".getBytes();
Reader targetReader = new InputStreamReader(new ByteArrayInputStream(initialArray));
targetReader.close();
}
2. With Guava
Next – let’s take a look at the Guava solution, also using an intermediary String:
@Test
public void givenUsingGuava_whenConvertingByteArrayIntoReader_thenCorrect()
throws IOException {
byte[] initialArray = "With Guava".getBytes();
String bufferString = new String(initialArray);
Reader targetReader = CharSource.wrap(bufferString).openStream();
targetReader.close();
}
Unfortunately the Guava ByteSource utility doesn’t allow a direct conversion, so we still need to use the intermediary String representation.
3. With Apache Commons IO
Similarly – Commons IO also uses an intermediary String representation to convert the byte[] to a Reader:
@Test
public void givenUsingCommonsIO_whenConvertingByteArrayIntoReader_thenCorrect()
throws IOException {
byte[] initialArray = "With Commons IO".getBytes();
Reader targetReader = new CharSequenceReader(new String(initialArray));
targetReader.close();
}
And there we have it – 3 simple ways to convert the byte array into a Java Reader. Make sure to check out the sample over on GitHub.