Luis Sep
Luis Sep

Reputation: 2412

getResource will always return null

This is driving me crazy. I have a simple eclipse project with a src folder and a class in it. But I can't seem to get getResource to find it. What am I doing wrong?

import java.net.URL;

public class ContextTest {

    public static void main(String[] args) {
        URL url = ContextTest.class.getResource("/src/ContextTest.java");
        System.out.println(url);
    }
}

If I right-click on the class name, the path is /TestsProject/src/ContextTest.java and the default classpath according to the Classpath tab in Run Configurations is TestProject.

It doesn't work with /bin/ContextTest.java , /ContextTest.java , ContextTest.java either.

Upvotes: 3

Views: 1226

Answers (2)

c.s.
c.s.

Reputation: 4826

When you load resources using ContextTest.class.getResource("/....") the leading / is translated as an absolute path. Here absolute means from your root package (i.e. the default package).

In Eclipse the root package is considered the one that is under the src folder. Your compiled classes will be placed under bin folder and if you create a jar you will see that your root package is not the src or bin folders but whatever folders are inside it. (for example com).

So the correct way to load a resource using a class absolute path would be ContextTest.class.getResource("/ContextTest.java");. If the file ContextTest.java is in the root package of wherever your compiled classes are, then it will be found and returned.

I hope this clears the picture.

Update: From the comments below it is not clear what you are trying to do. When you use getResource() you are not loading a file but a resource from the classpath. This would correctly find the resource even if your files were inside a jar file. So for your above example to work the file you are trying to load as a resource should be in the classpath (i.e. under bin folder since this is the root of your classpath when you execute from inside Eclipse). If you are trying to load a file outside of your classpath then don't try to load a resource, you could use File instead.

Upvotes: 3

Kevin Bowersox
Kevin Bowersox

Reputation: 94499

Resources accessed via getResource() must be on the classpath. Your Java files will be compiled and placed on the classpath. The compiled .java file will be given an extension of .class.

Try

 URL url = ContextTest.class.getResource("ContextTest.class");

Upvotes: 0

Related Questions