Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

like image 936
nburk Avatar asked Mar 23 '15 19:03

nburk


1 Answers

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.

like image 152
VGR Avatar answered Sep 30 '22 04:09

VGR