2010/09/28

Simply getting at a resource file in a Jar in Java.

Accessing resources in jar files.  I came across a need for this while attempting to not hard code in Java the some data that would be loaded into a HashMap.  The xml in question was conforming to NetBeans default '.ent' file naming.

Sifting through lots of cruft, applet loading specifics and other somewhat useless but informative and educational blather, I eventually ran across http://forums.sun.com/thread.jspa?threadID=5123126 and was rewarded with a straightforward snippet:

use : this.getClass().getClassLoader().getResourceAsStream(name)
example: myClass.getClass().getClassLoader().getResourceAsStream("res/my.gif")

two tips:
1 - use your own class that is in jar file. if used another class - for example Object - fails
2 - name i.e. resource must be without leading '/'

I then repurposed accordingly, since I was assuming XML for my org.w3c.dom.* stuff to parse the config with, I needed an InputStream implementation that could later be passed to the document object I was going to be letting those wonderful modules build for me.


InputStream xmlinstr = this.getClass().getClassLoader().getResourceAsStream("SomeFileAtTheRootOfMyJar.ent");

No comments: