Java Read Classpath Resource as Byte Array using Apache Commons IO

Tags: Classpath Resource IOUtils Apache Commons Apache Commons IO

In this Java tutorial, we learn how to read a classpath resource into a byte array using the IOUtils class of Apache Commons IO library.

How to add Apache Commons IO library to your Java project

To use the Apache Commons IO library in the Gradle build project, add the following dependency into the build.gradle file.

implementation 'commons-io:commons-io:2.8.0'

To use the Apache Commons IO library in the Maven build project, add the following dependency into the pom.xml file.

<dependency>
  <groupId>commons-io</groupId>
  <artifactId>commons-io</artifactId>
  <version>2.8.0</version>
</dependency>

To have more information about the Apache Commons IO library you can visit the library home page at commons.apache.org/proper/commons-io/

How to Read Classpath resource as byte array

For example, we have a file in classpath at src/main/resources/test.txt with the content as below.

http://simplesolution.dev

The Java program below, we use the IOUtils.resourceToByteArray() method to read the file content into a byte array.

ReadResourceToByteArray.java

import org.apache.commons.io.IOUtils;

import java.io.IOException;

public class ReadResourceToByteArray {
    public static void main(String... args) {
        try {
            byte[] contents = IOUtils.resourceToByteArray("/test.txt");
            for(byte value: contents) {
                System.out.print((char)value);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
The output is:
http://simplesolution.dev

Happy Coding 😊