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.

java-structure

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


import java.net.URL;

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]

 

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s