Extract Java resources from jar and ZIP files

Source: Internet
Author: User

Most Java programmers are very clear about the advantages of using jar files to package various resources (such as. class files, sounds, and images) that constitute the Java solution. A frequently asked question when using jar files is: "How to extract images from jar files ?" This article will answer this question and provide a class, which 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 to be used by our application. The following describes how to use jarresources to access image files in jar files:
    JarResources JR=new JarResources("GifBundle.jar");

    Image logo=Toolkit.getDefaultToolkit().createImage(JR.getResources("logo.gif"));

This Code shows that we can createJarResourcesObject, and initialize it as a jar file containing the resources we want to use --images.jar. Then we useJarResourcesOfgetResource()Methods: provide raw data from the logo.gif file tocreateImage()Method.Description
Jarresource is a simple example of how to use various functions provided by Java to process jar and ZIP files.

 Work Mode
JarReourcesImportant data fields of the class are used to track and store the content 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;

In this way, set the name of the JAR file for the class instantiation, and then goinit()Method to complete all the actual work.   public JarResources(String jarfilename) {
      this.jarfilename=jarfilename;
      init();
   }

Now,init()Method: load the entire content of the specified JAR file to a hashtable (accessed by resource name.

This is a very useful method. Next we will analyze it further.ZipFileClass provides us with basic access to the JAR/ZIP file header information. This is similar to the directory information in the file system. Below we listZipFileAll entries in, and add the size of each resource in the fileHtsizesHashtable:

 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();
Next, we use ZipInputStreamClass access file. ZipInputStreamClass completes all magic, allowing us to read each resource in the file separately. We read the exact number of bytes that constitute each resource from the archive and store it in HtjarcontentsIn hashtable, you can access the data using the Resource Name:      
          // extract resources and put them into the hashtable.
          FileInputStream fis=new FileInputStream(jarFileName);
          BufferedInputStream bis=new BufferedInputStream(fis);
          ZipInputStream zis=new ZipInputStream(bis);
          ZipEntry ze=null;
          while ((ze=zis.getNextEntry())!=null) {
             if (ze.isDirectory()) {
Continue; /// ah! No processed resources in the subdirectory.
             }
             if (debugOn) {
                System.out.println(
                   "ze.getName()="+ze.getName()+","+"getSize()="+ze.getSize()
                   );
             }
             int size=(int)ze.getSize();
             // -1 means unknown size. 
             if (size==-1) {
                size=((Integer)htSizes.get(ze.getName())).intValue();
             }
             byte[] b=new byte[(int)size];
             int rb=0;
             int chunk=0;
            while (((int)size - rb) > 0) {
                 chunk=zis.read(b,rb,(int)size - rb);
                 if (chunk==-1) {
                    break;
                 }
                 rb+=chunk;
             }
             // add to internal resource hashtable
             htJarContents.put(ze.getName(),b);
             if (debugOn) {
                System.out.println(
                   ze.getName()+" rb="+rb+
                   ",size="+size+
                   ",csize="+ze.getCompressedSize()
                   );
             }
          }
       } catch (NullPointerException e) {
          System.out.println("done.");
       } catch (FileNotFoundException e) {
          e.printStackTrace();
       } catch (IOException e) {
          e.printStackTrace();
       }
   }
Note that the name used to identify each resource is the qualified path name of the resource in the file, for example, NoClass name in the package-that is, in the java.util.zip package ZipEntryClass will be named "Java/util/zip/zipentry" instead of "java.util.zip. zipentry ".

Other methods:

    /**
    * Dumps a zip entry into a string.
    * @param ze a ZipEntry
    */
   private String dumpZipEntry(ZipEntry ze) {
       StringBuffer sb=new StringBuffer();
       if (ze.isDirectory()) {
          sb.append("d "); 
       } else {
          sb.append("f "); 
       }
       if (ze.getMethod()==ZipEntry.STORED) {
          sb.append("stored   "); 
       } else {
          sb.append("defalted ");
       }
       sb.append(ze.getName());
       sb.append("/t");
       sb.append(""+ze.getSize());
       if (ze.getMethod()==ZipEntry.DEFLATED) {
          sb.append("/"+ze.getCompressedSize());
       }
       return (sb.toString());
   }

    /**
    * Extracts a jar resource as a blob.
    * @param name a resource name.
    */
   public byte[] getResource(String name) {
      return (byte[])htJarContents.get(name);
   }
      
The last important part of the code is a simple test driver. The test driver is a simple application that receives the JAR/ZIP file name and Resource Name. It tries to find the resource file in the file and then reports the message of success or failure:
public static void main(String[] args) throws IOException {
       if (args.length!=2) {
          System.err.println(
             "usage: java JarResources < jar file name> < resource name>"
             );
          System.exit(1);
       }
       JarResources jr=new JarResources(args[0]);
       byte[] buff=jr.getResource(args[1]);
       if (buff==null) {
          System.out.println("Could not find "+args[1]+".");
       } else {
          System.out.println("Found "+args[1]+ " (length="+buff.length+").");
       }
   }
}              // End of JarResources class.
You have learned about this class. An easy-to-use class that hides all the thorny issues of using resources packaged in jar files. Summary
If you were eager to know how to extract images from a jar file, you have learned a method. With this new class provided by this technique, you can not only use jar files to process images, but also use the extraction magic in jar files. AnyResources.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.