Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
620 views
in Technique[技术] by (71.8m points)

java - 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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...