Read an image resource from a Jar file

Let’s first create an JAR file containing an image. Assuming that you have a GIF file called test.gif, type on the command line:

 
jar cvf Tester.jar test.gif

This will create the file Tester.jar.

Add this jar file to your classpath:

 
set classpath=%classpath%;C:Tester.jar

(“C:” or wherever you put your jar file).

The following piece of code shows you how the classloader is used to locate the resource (in this case “test.gif”) in the search path:

 
import java.net.*;
import javax.swing.*;
 
public class Tester {
    
   public ImageIcon loadImageFromJar(String imagename) {
      ImageIcon image = null;
 
      try {
         URLClassLoader cl = (URLClassLoader) getClass().getClassLoader();
         URL url = cl.findResource(imagename);
         image = new ImageIcon(url);
      } catch (Exception e) {
         System.err.println(e);
         System.exit(1);
      }
  
      return image;
   }   
 
   public static void main(String [] args) {
      Tester tester = new Tester();
 
      ImageIcon image = tester.loadImageFromJar("test.gif");
 
      System.out.println(image);
   }
}