Reading classpath file contents

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

“IOUtils” class provides a static method named “resourceToString”. This method reads the contents of the file and return a String object.

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

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 java.io.IOException;
import java.nio.charset.StandardCharsets;

public class Example8 {
    public static void main(String[] args) throws IOException {
        String result = IOUtils.resourceToString("example.properties", StandardCharsets.UTF_8, Example8.class.getClassLoader());
        System.out.println(result);
    }
}

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

I get a String as return value which is printed to the console.

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

Leave a comment