Accessing a resource within a .jar

Posted by Emanuele Gesuato Mon, 06 Feb 2006 01:08:00 GMT

Sometimes it is useful to distribute an application in a jar file through Java Web Start or any other way. So, you could have to read some resource (images or properties file) from inside a jar. How can you do it ? It’s very simple, here’s an example to retrieve an image:

ImageIcon image = (new ImageIcon(getClass().getResource("yourpackage/mypackage/image.gif")));

In general, you can retrieve an InputStream in the following way:

InputStream is = this.getClass().getClassLoader()    .getResourceAsStream("yourpackage/mypackage/myfile.xml");

It will run inside or outside the jar. Enjoy !

Posted in  | Tags ,  | 78 comments | no trackbacks

From which Jar a Class was loaded?

Posted by Paolo Dona' Sun, 13 Nov 2005 15:11:00 GMT

Sometimes in production environments I face problems never encountered during development… It’s a general thing.. could happen with jdbc drivers or xml parsers.

I just feel classes are loaded from a different jar than expected.

This of course could happen if you’re deploying to a very different application server or if you’ve no control over the production server classpath.

I found in javaalmanac.com a code snippet that can help you identify which is the jar containing a specific Class at runtime:

Class cls = MyFoo.class;
ProtectionDomain pDomain = cls.getProtectionDomain();
CodeSource cSource = pDomain.getCodeSource();
URL loc = cSource.getLocation(); 
System.out.println(loc); 
// prints something like "c:/jars/MyFoo.jar"

This way you can check if your class is loaded right from the expected jar, not elsewhere :-).

This has shown to be really useful during my sad production debug sessions.

Hope it can help you as well.

Tags , , ,  | 14 comments