Simiil
Simiil

Reputation: 2311

Resource loading in Java not working as it should

This is the well known problem of loading resources from a jar file. This is not the first time I've tried to do this, but now it doesn't work the way I expect it to.

Normally I try to load the Resources with this.getClass.getResource("foo.png"), or getResourceAsStream()and it works. Now however it does not. The Resource is always null.

If I let System.out.println(this.getClass.getResource("")) print me the path (from eclipse) it shows /path/to/eclipseproject/package/structure/. Running this from a jar it just shows rsrc:package/structure

If I recall correctly this should print the path to the jar. Furthermore I thought this would print the package structure in both cases. Am I doing something wrong?

Upvotes: 0

Views: 2656

Answers (5)

Rob Philipp
Rob Philipp

Reputation: 261

This answer provides an explanation of how to load class resources from JAR files, even when the class is not in the JAR file and not in the Class-Path specified in the JAR file's manifest. There are also links to code.

Upvotes: 0

b75.
b75.

Reputation: 94

Check the URLClassLoader for all the gory details, but it really depends on whether you are trying to access a ressource in the jar,

  • using a class loaded inside the same jar, in this case your file 'root' is the root of the jar

  • using a class loaded outside the jar (your eclipse case) where the root is your 'working directory'

To access resources inside a jar from outside, you should use something like

URL url = new URL( "jar", "", "file:" + jar.getCanonicalPath( ) + "!/" + localPathResource ); url.openStream(...)

Upvotes: 0

ahanin
ahanin

Reputation: 892

Unless you prepend the path to the resources with '/', Class.getResource() will search for the resource in class package. E.g.: tld.domain.Foo.class.getResource("Bar.txt") will search for tld/domain/Bar.txt

Upvotes: 0

TacB0sS
TacB0sS

Reputation: 10266

Here is the thing...

When Extracting the file from the Jar use:

this.getClass.getResource("/foo.png")

When running from a runnable Jar use, to reference an external file in the Jar folder path:

this.getClass.getResource("foo.png")
// When running this from Eclipse, it would refer to files in project root!

I have a code in the lower level determining where I'm running from to determine the correct path.

Upvotes: 2

lucrussell
lucrussell

Reputation: 5160

Doe this get the path you need?

this.getClass().getClassLoader().getResource("<your class name>.class").getPath();

See also this question for more on this issue.

Upvotes: 0

Related Questions