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.

Related posts:

Java Program to Perform String Matching Using String Library
Java Program to Implement Sorting of Less than 100 Numbers in O(n) Complexity
Request a Delivery / Read Receipt in Javamail
Spring Data Java 8 Support
Java Program to Check if a Point d lies Inside or Outside a Circle Defined by Points a, b, c in a Pl...
Java Program to Implement WeakHashMap API
Introduction to Spring Method Security
@DynamicUpdate with Spring Data JPA
Java Concurrency Interview Questions and Answers
Giới thiệu về Stream API trong Java 8
Java Program to Perform Optimal Paranthesization Using Dynamic Programming
HashSet trong Java hoạt động như thế nào?
Removing Elements from Java Collections
Java Program to Implement Sorted Vector
Create Java Applet to Simulate Any Sorting Technique
Intro to Spring Boot Starters
Handle EML file with JavaMail
Iterating over Enum Values in Java
A Guide to @RepeatedTest in Junit 5
Giới thiệu Design Patterns
JUnit5 Programmatic Extension Registration with @RegisterExtension
Java Program to Perform Addition Operation Using Bitwise Operators
Java Program to implement Bi Directional Map
Java Program to Implement the Vigenere Cypher
Using Spring @ResponseStatus to Set HTTP Status Code
Lớp TreeMap trong Java
Giới thiệu JDBC Connection Pool
So sánh ArrayList và LinkedList trong Java
Feign – Tạo ứng dụng Java RESTful Client
Join and Split Arrays and Collections in Java
Java Program to Check if a Given Binary Tree is an AVL Tree or Not
Map Serialization and Deserialization with Jackson