Trouble loading resources from inside JAR file...

Hi there.

I am having some problems loading resources from within a jar file, and I don’t really know why…

Scenario: Project A (the “executable” project) uses project B ( lib project ).
Project B contains a class for loading resources.

It loads resources the typical way with MyClass.class.getClassLoader().getResource(…)

Now, while using Eclipse, this works great ( after setting some extra src folders. I have a src/bin setup for source files / compiled files ).

I did some basic tests, printing out various resource locations. For instance, take MyClass.class.getClassLoader().getResource(".");
In Eclipse, it rightly returns the folder from which Project A is launched. However, in the jar file, it returns null. In fact, everything I tried as a resource returned null.

Comparing the eclipse project files with the jar extracted confirms that the paths seem correct…

Anyone got an idea of what’s going on here?

Yes, You cannot access files within a JAR using getResource(). You must use getResourceAsStream().

The reason it works in eclipse is because it executes it using class files not a JAR.

You can, in fact, use getResource() from within a JAR file. What you can’t do is use getResource().getFile()

What you are facing may be related to the classloader. I would try getClass().getResource(…)

I just posted an example with source code last night of a JAR reading a file using getClass().getResource(…) … see if that works for you.

Thanks, I got it working. I must have been very tired when I had the problem… Hehe. I was attempting to reach directories. Naturally this works well outside a jar, but not so well inside it, since the structure is flat. Oh well :slight_smile: It was a typical ‘DOH’ problem.