Java – Get the path of a file from the resources folder

Sometimes, you may wish to get the path of a file or resource stored within you resources folder. The java snippet below will help you return the path to a resource placed in the resources folder.


Consider the code structure displayed above, the file we wish to get the path to is called “a.txt”.


public class Main {

    public static void main(String[] args) {
        Main main = new Main();
        System.out.println("Path = [" + main.getPath("file/a.txt") + "]");

    private String getPath(String fileName) {
        ClassLoader classLoader = getClass().getClassLoader();
        URL resource = classLoader.getResource(fileName);
        return resource.getPath();

The output is shown below

Path = [/D:/Personal/JavaCodes/Blog/out/production/Blog/file/a.txt]