views:

169

answers:

4
A: 

getClass().getResource() will look for a resource with the specified name starting from (relative to) the package the class on which you call getClass() is called.

if you want the resource relative from the root of the jar, then you should do getClass().getClassLoader().getResource()

Stefan De Boey
I just tried it, and it still threw a null pointer exception. Could it be a problem that my resource folder is not a src folder?
chama
yes, the reources should be on the classpath
Stefan De Boey
+2  A: 

From the documentation of Class:

Before delegation, an absolute resource name is constructed from the given resource name using this algorithm:

  • If the name begins with a '/' ('\u002f'), then the absolute name of the resource is the portion of the name following the '/'.

  • Otherwise, the absolute name is of the following form: modified_package_name/name

Where the modified_package_name is the package name of this object with '/' substituted for '.' ('\u002e').

So you probably want

getResource("/settings.png")

or

getResource("/resources/settings.png")

or something similar, depending on your classpath, I believe.

Toon Van Acker
A: 

If you do not want to mess with the classpath and anyway, in any case, there's an overkill but 100% foolproof method that works that is based on the two following facts:

  • it is always possible to find where the .jar that your class was (class)loaded from is located

  • a .jar file is simply a zip file and Java has a default API allowing to read zip files.

It is overkill, but it "Just Works [TM]" (and due to various guarantees made by Java it cannot not work: you can always find the path to a .jar and always read from that .jar) and is convenient when you want to create a unique .jar that can be launched as is on Windows, OS X, Linux, etc.

We're using this overkill method on an app that is deployed on hundreds of different systems.

Webinator
A: 

ok, this might sound weird but it surely works worked for me after getting stuck for more than a month.when passing the url use (gif or png) in caps like .GIF or .PNG