Getting URL of classpath resource

In this post under Apache Commons IO, I will show with example how to get URL of a resource present in application classpath.

“IOUtils” class provides a static method “resourceToURL” which takes the resource name and the classloader as arguments and returns url of the resource.

Below is the main class showing how to use “IOUtils.resourceToURL” method.

Main class

package ioutils;

import org.apache.commons.io.IOUtils;

import java.io.IOException;
import java.net.URL;

public class Example4 {
    public static void main(String[] args) throws IOException {
        URL url = IOUtils.resourceToURL("example.properties", Example4.class.getClassLoader());
        System.out.println(url.toString());
    }
}

For our example I have “example.properties” file under “src\resources” folder.

In the above code, at line 10, I call “resourceToURL” method. Passed the resource name and classloader instance as arguments to the method.

This method will return an instance of java “URL” class which is printed at line 11.

In this way we can get url of a classpath resource.

Leave a comment