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.
