Java – Reader to Byte Array

This quick tutorial will show how to convert a Reader into a byte[] using plain Java, Guava and the Apache Commons IO library.

This article is part of the “Java – Back to Basic” series here on VietMX’s Blog.

1. With Java

Let’s start with the simple Java solution – going through an intermediary String:

@Test
public void givenUsingPlainJava_whenConvertingReaderIntoByteArray_thenCorrect() 
  throws IOException {
    Reader initialReader = new StringReader("With Java");

    char[] charArray = new char[8 * 1024];
    StringBuilder builder = new StringBuilder();
    int numCharsRead;
    while ((numCharsRead = initialReader.read(charArray, 0, charArray.length)) != -1) {
        builder.append(charArray, 0, numCharsRead);
    }
    byte[] targetArray = builder.toString().getBytes();

    initialReader.close();
}

Note that the reading is done in chunks, not one character at a time.

2. With Guava

Next – let’s take a look at the Guava solution – also using an intermediary String:

@Test
public void givenUsingGuava_whenConvertingReaderIntoByteArray_thenCorrect() 
  throws IOException {
    Reader initialReader = CharSource.wrap("With Google Guava").openStream();

    byte[] targetArray = CharStreams.toString(initialReader).getBytes();

    initialReader.close();
}

Notice that we’re using the built in utility API to not have to do any of the low-level conversion of the plain Java example.

3. With Commons IO

And finally – here’s a direct solution that is supported out of the box with Commons IO:

@Test
public void givenUsingCommonsIO_whenConvertingReaderIntoByteArray_thenCorrect() 
  throws IOException {
    StringReader initialReader = new StringReader("With Commons IO");

    byte[] targetArray = IOUtils.toByteArray(initialReader);

    initialReader.close();
}

And there you have it – 3 quick ways to transform a java Reader into a byte array. Make sure to check out the sample over on GitHub.