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

2

5

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

Desmonddesmoulins answered 23/3, 2015 at 19:58 Comment(0)
D
6

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.

Declivitous answered 23/3, 2015 at 20:11 Comment(1)
Great explanation! :)Haileyhailfellowwellmet
O
1

http://docs.oracle.com/javase/7/docs/api/java/lang/Class.html#getResource(java.lang.String)

The rules for searching resources associated with a given class are implemented by the defining class loader of the class. This method delegates to this object's class loader. If this object was loaded by the bootstrap class loader, the method delegates to ClassLoader.getSystemResource(java.lang.String). Before delegation, an absolute resource name is constructed from the given resource name using this algorithm:

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').

Orelia answered 23/3, 2015 at 20:5 Comment(2)
thanks for the reply! so, if understand correctly, in my case the following applies: If the name begins with a '/' ('\u002f'), then the absolute name of the resource is the portion of the name following the '/'. but why is it that this is not a valid resource then?Desmonddesmoulins
The easiest way to understand is to use getResource("") with an empty String. This will give you the URL of the package your class is in. Then just sysout that URL and you will understand.Orelia

© 2022 - 2024 — McMap. All rights reserved.