Why does class.getResource() keep returning null although there is a resource at the specified path?

nburk picture nburk · Mar 23, 2015 · Viewed 9.5k times · Source

I am wondering why the method getResource keeps returning null, I have the following setup:

public static URL getResource(String path){
    URL url = ResourceLoader.class.getResource(path);
    if (Parameters.DEBUG){
        System.out.println(path);
    }
    return url;
}

My project structure in Eclipse is as follows:

-- res
  -- img

The path variable I pass to getResource has the value "/res/img" or "/res/img/smile.png". Yet the method keeps returning null and url is not set. I also followed the instructions of this question, which were to add the folder to the project's classpath via Run configurations, still without success... Does anyone know what I am doing wrong?

enter image description here

Answer

VGR picture VGR · Mar 23, 2015

Short answer: Use "/img/smile.png".

What's actually happening is that any path starting with / which is given to the Class.getResource method is always treated as being relative to each entry in the classpath.

As your screenshot shows, the res directory is such a classpath entry. So the Class.getResource method treats the path you provide as relative to that entry. Meaning, relative to the res directory.

So, the method combines your string argument with that directory, which results in res/res/img/smile.png. Since no file (resource) exists at that location, it returns null.