View RSS Feed

My Java Tips

Accessing Resources in a JAR File

Rate this Entry
by , 11-28-2011 at 06:05 PM (2793 Views)
JAR files are used to deploy applications. They comprise of java classes and other resources like images etc. In this post, I will explain how to access resources packed in a JAR file.



To access resources in a JAR file, we use getResource method. Lets do this practically. The code snippet provided shows how to retrieve images from a JAR file.

Java Code:
// Get current classloader
ClassLoader cl = this.getClass().getClassLoader();
// Create icons
Icon saveIcon = new ImageIcon(cl.getResource("images/save.gif"));
Icon cutIcon = new ImageIcon(cl.getResource("images/cut.gif"));
The example assumes that the following entries exist in the JAR file.

-images/save.gif
-images/cut.gif

Hope this helps.

Submit "Accessing Resources in a JAR File" to Facebook Submit "Accessing Resources in a JAR File" to Digg Submit "Accessing Resources in a JAR File" to del.icio.us Submit "Accessing Resources in a JAR File" to StumbleUpon Submit "Accessing Resources in a JAR File" to Google

Categories
Java SE

Comments