2

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
  • The new File("relative_path") way of opening a file depends on where you started the process from. The MyClass.class.getClass()... way I think requires the resources to be in the same directory as the source code, so try shifting it into the 'main' folder and see if that works... Dec 28, 2015 at 16:13

1 Answer 1

6

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.

1
  • 2
    finally after searching the internet for hours, this solves the problem Jun 19, 2019 at 10:49

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.