getClass().getResource() always returning null

2019-01-19 13:59发布

I am trying to set the URL of an image that is located in my resource folder in my src folder. It is always setting the URL to null. The image is there and everything is named correctly. What is the issue? Thanks!

My file structure:

  • sp1
    • src
      • resources
        • 01.png

Here is my code where i am trying to set the URL for the picture:

this.setImagePath(getClass().getResource("/resources/01.png"));

And the setImagePath is doing this, i am sure this is not the problem, because i followed the execution and it is setting it equal to null.

public final void setImagePath(URL imagePath) {
    this.imagePath = imagePath;
}

Solution

I had to clean the build and rebuild. It worked after that fix.

Thanks

4条回答
看我几分像从前
2楼-- · 2019-01-19 14:18

I would guess the URL should be "01.png" not "/resources/01.png"

查看更多
冷血范
3楼-- · 2019-01-19 14:25

You need to check that, however you're building, the image file gets copied over to wherever the class files are compiled to. I.e. if your class is com.foo.MyImageLoader and located at <build dir>/com/foo/MyImageLoader.class, then the image should be at <build dir>/resources/01.png for you to be able to load it like that.

查看更多
Melony?
4楼-- · 2019-01-19 14:27

I had to clean the build and then rebuild. Works now.

查看更多
仙女界的扛把子
5楼-- · 2019-01-19 14:33

If using JDeveloper, make sure that you have the extension of the file that you want copied to the classes folder for use selected. Right click on the project and choose project properties to get to this screen.

JDeveloper

查看更多
登录 后发表回答