Most Java programmers are very clear about the advantages of using jar files to package the various resources (that is,. class files, sounds, and images) that make up a Java solution. One question often asked by people who just started using jar files was: "How do I extract images from a jar file?" "This article will answer this question and will provide a class that makes it very easy to extract any resources from the jar file!"
Load GIF image
Suppose we have a jar file that contains a set of. gif images that our application will use. Here's how to access an image file in a jar file using jarresources:
Jarresources jr=new jarresources ("Gifbundle.jar");
Image Logo=toolkit.getdefaulttoolkit (). CreateImage (Jr.getresources ("logo.gif"));
This code shows that we can create a Jarresources object and initialize it to the jar file that contains the resource we want to use--Images.jar. We then use the Jarresources getresource () method to supply the original data from the Logo.gif file to the CreateImage () method of the AWT Toolkit.
Naming instructions
Jarresource is a very simple example of how you can use the various features provided by Java to process jars and zip files.
Working mode
Important data fields for the Jarreources class are used to track and store the contents of the specified JAR file:
public final class JarResources {
public boolean debugon=false;
private Hashtable htsizes=new Hashtable();
private Hashtable htjarcontents=new Hashtable();
private String jarfilename;
This way, the instantiation of the class sets the name of the jar file and then goes to the init () method to complete all the actual work.
public JarResources(String jarfilename) {
this.jarfilename=jarfilename;
init();
}
The init () method now loads only the entire contents of the specified jar file into a hashtable (accessed through a resource name).
This is a fairly useful method, and we'll make a further analysis of it below. The ZipFile class provides us with basic access to Jar/zip file header information. This is similar to the directory information in the file system. Here we list all the entries in the ZipFile and add the htsizes hashtable to the size of each resource in the file:
private void init() {
try {
// extracts just sizes only.
ZipFile zf=new ZipFile(jarFileName);
Enumeration e=zf.entries();
while (e.hasMoreElements()) {
ZipEntry ze=(ZipEntry)e.nextElement();
if (debugOn) {
System.out.println(dumpZipEntry(ze));
}
htSizes.put(ze.getName(),new Integer((int)ze.getSize()));
}
zf.close();