Dashboard > People > Hildeberto Mendonça > ... > Headaches > How a jar file application can access files in itself

The distribution of an application in a network is not a problem when we are using the Java platform. A web application already has a distributed architecture and a stand-alone application is distributed by Java WebStart. According to Wikipedia, Java WebStart was born 5 years ago, so we can conclude that it has the necessary maturity to be applied in production time.

When we try to distribute something using Java Webstart, the first thing that comes to our minds is how to compact all resources in only one jar file. Yes, it is easy too. Good IDEs like Netbeans and Eclipse provide it by default. But, if you need to access images or files inside of the jar, the code is not self evident. To load a XML file, for example, you have to use the code below:

...
ClassLoader cl = this.getClass().getClassLoader();
java.io.InputStream in = cl.getResourceAsStream("conf/properties.xml");
...

The file "properties.xml" is inside of the "application.jar" file, that is stored in the "conf" package.

When you want to access images from the jar file the code is a little bit different. The example below shows how to create an image icon to illustrate Java components.

...
// When the image file is in the same package of the class 'SearchTab'.
new ImageIcon(SearchTab.class.getResource("magnifyingGlass.png");

// When the image file is in another package of the jar file.
ClassLoader cl = this.getClass().getClassLoader();
JButton btRemove = new JButton(new ImageIcon(cl.getResource("images/remove.png")));

The Java API doesn't provide one form to change files inside of jar files. We can read and manipulate the content, but not save it back, in the same file.

Back

Design: Felipe Martins - Webmaster: Israel Freitas