Cannot load resource in jar

2019-08-31 16:38发布

I am trying to load a resource in a jar, here is the exported jar: enter image description here

'main' is the package with all my classes, and in one of those classes I am trying to load the background.png file. In my Eclipse project I put the resources under a "res/" folder, which I added to the build path to include it. When I try to use

new File("background.png");

It can't find the file. When I use

MyClass.class.getClass().getClassLoader().getResource("background.png");

It still can't find the file.

1条回答
做个烂人
2楼-- · 2019-08-31 17:00

Files packaged in a jar can't be accessed as File objects.

When you try

MyClass.class.getClass().getClassLoader().getResource("background.png");

you are actually using the ClassLoader of java.lang.Class and not of main.MyClass which may not be able to find the resource (in case it is the system classloader). Try

MyClass.class.getClassLoader().getResource("background.png");

instead.

查看更多
登录 后发表回答