Java Get the URL of Classpath Resource using Apache Commons IO

Tags: Classpath Resource URL IOUtils Apache Commons Apache Commons IO

In this Java tutorial, we learn how to get the URL of a classpath resource using the IOUtils class of Apache Commons IO library.

How to add Apache Commons IO library to your Java project

To use the Apache Commons IO library in the Gradle build project, add the following dependency into the build.gradle file.

implementation 'commons-io:commons-io:2.8.0'

To use the Apache Commons IO library in the Maven build project, add the following dependency into the pom.xml file.

<dependency>
  <groupId>commons-io</groupId>
  <artifactId>commons-io</artifactId>
  <version>2.8.0</version>
</dependency>

To have more information about the Apache Commons IO library you can visit the library home page at commons.apache.org/proper/commons-io/

How to get the URL of a Classpath Resource

For example, we have a file in classpath at src/main/resources/test.txt

The Java program below, we use the IOUtils.resourceToURL() method to get the URL of the above classpath resource file.

GetURLOfResource.java

import org.apache.commons.io.IOUtils;

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

public class GetURLOfResource {
    public static void main(String... args) {
        try {
            URL url = IOUtils.resourceToURL("/test.txt");

            System.out.print(url);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
The output is:
file:/D:/JavaApacheCommonsIO/build/resources/main/test.txt

Happy Coding 😊