The javadoc for Class.getResourceAsStream() documents the lookup logic:

If the name begins with a '/' ('\u002f'), then the absolute name of the resource is the portion of the name following the '/'.

Otherwise, the absolute name is of the following form:
modified_package_name/name

Where the modified_package_name is the package name of this object with '/' substituted for '.' ('\u002e').

So in other words, the resource name passed to the method should look like /com/package/p2/props.properties if the props.properties is stored in the com.package.p2 package instead of the current class's.

Answer from matt b on Stack Overflow
🌐
Baeldung
baeldung.com › home › spring › access a file from the classpath in a spring application
Access a File from the Classpath using Spring | Baeldung
March 26, 2025 - Note that from Resource, we can easily jump to Java standard representations like InputStream or File. Another thing to note here is that the above method works only for absolute paths. If we want to specify a relative path, we can pass a second class argument. The path will be relative to this class: new ClassPathResource("../../../data/employees.dat", Example.class).getFile(); The file path above is relative to the Example class. ... public Resource loadEmployeesWithResourceLoader() { return resourceLoader.getResource( "classpath:data/employees.dat"); }
🌐
GeeksforGeeks
geeksforgeeks.org › java › loading-resources-from-classpath-in-java-with-example
Loading Resources from Classpath in Java with Example - GeeksforGeeks
July 23, 2025 - So basically two methods named: getResource() and getResourceAsStream() are used to load the resources from the classpath. These methods generally return the URL's and input streams respectively.
🌐
Blogger
javarevisited.blogspot.com › 2014 › 07 › how-to-load-resources-from-classpath-in-java-example.html
How to Load Resources from Classpath in Java with Example
Here is our complete Java program to load images, resources, configuration files, property files, text files, or binary files from classpath in Java, Resources can be anything, what is important is that they must be accessible.
🌐
Xenovation
xenovation.com › home › blog › java › java - read file from classpath
Java - Read file from classpath | XENOVATION
April 24, 2019 - In any case it is recommended to always use absolute paths to access the file in the classpath. Here is an example of using getClass().getResource() and ClassLoader: package myTestPackage; import java.io.IOException; import java.net.URL; import java.nio.file.Files; import java.nio.file.Paths; public class Examples { private static final String line = "-----------------------------------------"; private void loadResource (String resource) throws IOException { URL u = this.getClass().getResource(resource); loadResourceByUrl(u, resource); } private void loadResourceWithContextLoader (String resou
🌐
TutorialsPoint
tutorialspoint.com › loading-resources-from-classpath-in-java-with-example
Loading Resources from classpath in Java with Example
July 28, 2023 - In summary, there exist diverse methods of loading resources from classpath in Java-such as utilizing ClassLoader.getResource() or ClassLoader.getResourceAsStream(). Subsequently, determining which mode to apply is contingent on individual usage criteria and respective requisites of your app.
🌐
Mkyong
mkyong.com › home › java › java – read a file from resources folder
Java - Read a file from resources folder - Mkyong.com
September 4, 2020 - In Java, we can use getResourceAsStream or getResource to read a file or multiple files from a resources folder or root of the classpath.
🌐
LogicBig
logicbig.com › how-to › java › different-ways-to-load-resources.html
What are different ways to load classpath resources in Java?
November 4, 2018 - ClassLoader.getSystemClassLoader().getResource(resourceName): Same as context class loader, it only works without a leading slash '/'. We can use <resources> in pom.xml to override default resource location. In the followings, we are specifying 'java' and 'resources' directories as resources.
Find elsewhere
🌐
Java Code Geeks
javacodegeeks.com › home › core java
How to Load Resources from Classpath in Java with Example
August 1, 2014 - Here is our complete Java program to load images, resources, text file or binary file from classpath in Java, resource can be anything, what is important is that it must be accessible.
🌐
Oracle
docs.oracle.com › javase › 8 › docs › technotes › guides › lang › resources.html
Location-Independent Access to Resources
April 21, 2026 - Methods in the classes Class and ClassLoader provide a location-independent way to locate resources. For example, they enable locating resources for: An applet loaded from the Internet using multiple HTTP connections. An applet loaded using JAR files. A Java Bean loaded or installed in the CLASSPATH.
🌐
Rip Tutorial
riptutorial.com › load a resource from the classpath
Java Language Tutorial => Load a resource from the classpath
By using the classloader, we need to specify the fully qualified path of our resource (each package). Or alternatively, we can ask the Test class object directly · InputStream is = Test.class.getResourceAsStream("file.txt"); Using the class ...
🌐
Coderanch
coderanch.com › t › 588460 › java › Loading-resource-jar-classpath
Loading resource from different jar on classpath (Java in General forum at Coderanch)
John Coss wrote:My conclusion, for the time being is, that on classpath only resources from jar than contains requested static main method are loaded. Resources from other jar files are unavailable, except for java compiled class files. I would disagree, as I was able to load XML files from other jars using your getResourceAsStream().
🌐
DevTut
devtut.github.io › java › resources-on-classpath.html
Java - Resources (on classpath)
Loading default configuration, Loading an image from a resource, Finding and reading resources using a classloader, Loading same-name resource from multiple JARs
Top answer
1 of 14
368

Intro and basic Implementation

First up, you're going to need at least a URLStreamHandler. This will actually open the connection to a given URL. Notice that this is simply called Handler; this allows you to specify java -Djava.protocol.handler.pkgs=org.my.protocols and it will automatically be picked up, using the "simple" package name as the supported protocol (in this case "classpath").

Usage

new URL("classpath:org/my/package/resource.extension").openConnection();

Code

package org.my.protocols.classpath;

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

/** A {@link URLStreamHandler} that handles resources on the classpath. */
public class Handler extends URLStreamHandler {
    /** The classloader to find resources from. */
    private final ClassLoader classLoader;

    public Handler() {
        this.classLoader = getClass().getClassLoader();
    }

    public Handler(ClassLoader classLoader) {
        this.classLoader = classLoader;
    }

    @Override
    protected URLConnection openConnection(URL u) throws IOException {
        final URL resourceUrl = classLoader.getResource(u.getPath());
        return resourceUrl.openConnection();
    }
}

Launch issues

If you're anything like me, you don't want to rely on a property being set in the launch to get you somewhere (in my case, I like to keep my options open like Java WebStart - which is why I need all this).

Workarounds/Enhancements

Manual code Handler specification

If you control the code, you can do

new URL(null, "classpath:some/package/resource.extension", new org.my.protocols.classpath.Handler(ClassLoader.getSystemClassLoader()))

and this will use your handler to open the connection.

But again, this is less than satisfactory, as you don't need a URL to do this - you want to do this because some lib you can't (or don't want to) control wants urls...

JVM Handler registration

The ultimate option is to register a URLStreamHandlerFactory that will handle all urls across the jvm:

package my.org.url;

import java.net.URLStreamHandler;
import java.net.URLStreamHandlerFactory;
import java.util.HashMap;
import java.util.Map;

class ConfigurableStreamHandlerFactory implements URLStreamHandlerFactory {
    private final Map<String, URLStreamHandler> protocolHandlers;

    public ConfigurableStreamHandlerFactory(String protocol, URLStreamHandler urlHandler) {
        protocolHandlers = new HashMap<String, URLStreamHandler>();
        addHandler(protocol, urlHandler);
    }

    public void addHandler(String protocol, URLStreamHandler urlHandler) {
        protocolHandlers.put(protocol, urlHandler);
    }

    public URLStreamHandler createURLStreamHandler(String protocol) {
        return protocolHandlers.get(protocol);
    }
}

To register the handler, call URL.setURLStreamHandlerFactory() with your configured factory. Then do new URL("classpath:org/my/package/resource.extension") like the first example and away you go.

JVM Handler Registration Issue

Note that this method may only be called once per JVM, and note well that Tomcat will use this method to register a JNDI handler (AFAIK). Try Jetty (I will be); at worst, you can use the method first and then it has to work around you!

License

I release this to the public domain, and ask that if you wish to modify that you start a OSS project somewhere and comment here with the details. A better implementation would be to have a URLStreamHandlerFactory that uses ThreadLocals to store URLStreamHandlers for each Thread.currentThread().getContextClassLoader(). I'll even give you my modifications and test classes.

2 of 14
117
URL url = getClass().getClassLoader().getResource("someresource.xxx");

That should do it.

🌐
Blogger
javarevisited.blogspot.com › 2014 › 07 › how-to-load-resources-from-classpath-in-java-example.html
Javarevisited: How to Load Resources from Classpath in Java with Example
The first example looks cleaner than the second example because we don't need to open an explicit stream, the getResourceAsStream() method returns an InputStream, which can be used anywhere. That's all on how to load resources from class-path in Java.
🌐
Spring
docs.spring.io › spring-framework › docs › 3.2.x › spring-framework-reference › html › resources.html
6. Resources
This class represents a resource which should be obtained from the classpath. This uses either the thread context class loader, a given class loader, or a given class for loading resources. This Resource implementation supports resolution as java.io.File if the class path resource resides in ...
🌐
Rip Tutorial
riptutorial.com › resources (on classpath)
Java Language Tutorial => Resources (on classpath)
The methods of ClassLoader accept a path-like resource name as an argument and search each location in the ClassLoader’s classpath for an entry matching that name.
🌐
How to do in Java
howtodoinjava.com › home › i/o › reading a file from classpath in java
Reading a File from Classpath in Java
April 11, 2022 - To read any file from the classpath in a class, we have to get the reference of the system classloader for that class that is trying to read the file. System classloader obviously knows the other paths for the application.
🌐
Micwan88
micwan88.github.io › java › 2018 › 10 › 10 › java-getResourceAsStream.html
Load resource file by getResourceAsStream in static method of Java | Web Notes for Michael Wan
October 10, 2018 - Sometimes static calling SomeClass.class.getClassLoader().getResourceAsStream() and SomeClass.class.getClass().getResourceAsStream() to load a resource file for webapp may not work properly as Application Server may use complex hierarchy ClassLoader for webapp. So the solution is as below: //If call from static method Thread.currentThread().getContextClassLoader().getResourceAsStream(resourcesName); //If it is not from static method this.getClass().getResourceAsStream(resourcesName);