Reading classpath file contents as bytes

In this post under Apache Commons IO, I will show with example how to read the contents of file present in your projects classpath as bytes.

“IOUtils” class provides a static method named “resourceToByteArray”. This method reads the contents of the file as bytes.

This method takes two arguments
1) the file name
2) the ClassLoader instance

This method returns a byte array.

Below is the complete main code for your reference.

We are reading “example.properties” file which we have added in our project classpath.

Main class

package ioutils;

import org.apache.commons.io.IOUtils;
import org.apache.commons.io.LineIterator;

import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.List;

public class Example7 {
    public static void main(String[] args) throws IOException {
        byte[] byteResult = IOUtils.resourceToByteArray("example.properties", Example7.class.getClassLoader());
        String stringResult = new String(byteResult, StandardCharsets.UTF_8);
        System.out.println(stringResult);
    }
}

In the above code, at line 14, I call “resourceToByteArray” method, pass the file name and classloader instance as an argument.

I get byte array as return value, which is converted to String at line 15.

At line 16, I print the contents to the console.

In this way we can read a file present in our project classpath as bytes.

Leave a comment