Saturday, December 20, 2008

Acessing Resources Inside of Jar Files

A short post to document a special detail in swing applications that causes an annoying waste of time. As a clever programmer, you always distribute your applications in JAR (Java achieve) packages, but you also put nice icons in your application to make it more attractive for final users and put some default configurations for basic initializations. The annoying problem (but easy to solve) is to package images and other files in a JAR file and create portable links to those files.

If you need to access a text file inside a JAR, the code is not self evident, but easy. To load an XML file, for example, you have to use the code below:

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


The file "properties.xml" is inside the "application.jar" file, in the same package of the class where it is called. You can put this file in another package, but it will be more difficult to define the exact location of it. It's easier and coherent if you keep the caller and the resource in the same place.

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 swing components.

JButton btRemove = new JButton(new ImageIcon(SearchTab.class.getResource("remove.png"));

Again, the figure "remove.png" is in the same package of the class "SearchTab.class".
The Java API doesn't provide one form to change files inside jar files. We can read and manipulate the content, but not save it back in the same file. So, this is a solution for read-only needs.

4 comments:

  1. Simple but great article Hildeberto. Solved me a problem other day. =)
    ReplyDelete
  2. thanks a lot for this post, Hildeberto! it helped me. yipeeeeeeeeeeee! my images, inside jar were not loading. i was continuously finding a solution for it from past 4-5 days. finally i got it. thanks a ton again! :-)
    ReplyDelete
  3. Hey
    Great Article. But I have to access a folder and give it's path to a library that I am using. That library then uses the files present in that folder. So, Can you help me with that ?
    Thanks.
    ReplyDelete
  4. Hi,

    that's difficult to visualize what you want. You probably need Java IO or Java New IO to do that. You can simple create a object File f = new File("c:/java") and pass it to your library, but it really depends on the case. There are many possibilities :)
    ReplyDelete