I just announced the new Spring 5 modules in REST With Spring:

>> CHECK OUT THE COURSE

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.

I just announced the new Spring 5 modules in REST With Spring:

>> CHECK OUT THE LESSONS

  Subscribe  
newest oldest most voted
Notify of
psualum0000
Guest

Why would would you use anything other than the java approach? What are the benefits of the other approach?

Eugen Paraschiv
Guest

The reasons I have seen all 3 approaches in different projects is mainly consistency. If your project does a lot of IO work, you’ll probably pick one library and go with it. So – if you pick for example Guava, the idea is to consistently use Guava across the board.
The other concern is memory use – it would be interesting to test out the Guava approach vs the other two, but my guess is that it would be more efficient.
Hope that helps. Cheers,
Eugen.