Java Tips 49: How to extract Java resources from JAR and ZIP file files
Are you just starting to contact JAR files? This new class can help you solve the problem!
Author:
John D. Mitchell and Arthur Choi
Abstract Package a class of Java resources in a Java Archive (JAR) file is a great way to shorten the download time, enhance security and enhance manageability. This tip shows how to easily extract resources from the JAR file for yourself.
Most Java programmers are very clear that the use of JAR files will form a variety of resources of the Java solution (ie .class file, sound, and image) package. (Please refer to the text if you are not familiar with the JAR file.
Reference resource section. One question that is often asked when I started using JAR files is: "How to extract images from JAR files?" This article will answer this question and provide a class, this class makes any resource from the JAR file. very simple!
Loading GIF images assumes that we have a JAR file that contains a set of .GIF images to use. Below is a way to access image files in the JAR file using JarResources:
JarResources jar = new jarresources ("images.jar"); image logo = Toolkit.getDefaultToolkit (). CreateImage (Jar.GetResource ("Logo.gif");
This code shows that we can create a JarResources object and initialize it to the JAR file that contains the resources we want to use - images.jar. We then use the jarresources' getResource () method to provide the original data from the logo.gif file to the CreateImage () method () method () method () method () method ().
Naming Description JarResource is a very simple example, which illustrates how to use the functions provided by Java 1.1 to handle JAR and ZIP file files.
A brief description of naming. The archiving support in Java is actually starting with the popular ZIP archive format (see "Java Tip 21: Use Archive Files To Speed Up Applet Loading"). Therefore, when Java support for processing file files is initially implemented, all types of files, such as this, are not placed in the java.util.zip package; these classes are usually starting with "ZIP". However, when turning to Java 1.1, the function has changed, and the name of the file file is also more Java feature. Therefore, now we call the files of JAR files basically ZIP files.
The important data domain of the JarResources class is 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;
In this way, the instantiation of this class sets the name of the JAR file, and then goes to the init () method to complete all the actual work.
Public JarResources {this.jarfilename = jarfilename; init ();} Now, init () method only loads the entire content of the specified JAR file to a HashTable (via resources).
This is a quite useful way, and we have further analyzed it. The Zipfile class provides us with basic access to JAR / ZIP file information. This is similar to the directory information in the file system. Below we list all entries in zipfile and add HTSIZES HashTable with each resource in the file:
Private vid init () {Try {zipfile zf = new zipfile (jarfilename); enumeration E = zf.entries (); while (e.hasMoreElements ()) {zipenTry Ze = (zipentry) E.NEXTELEMENT (); if (Debugon ) {System.out.println;} htsizes.put (ZE.GETNAME (), new integer ((int) ZE.GETSIZE ()));} zf.close ();
Next, we use the ZipInputStream class to access the file. The ZipinputStream class completes all magic, allowing us to separately read each resource in the file. We read the number of exact bytes that make up each resource from the file and store it in htjarcontents hashtable, you can access these data through the resource name:
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.Indirectory ()) {Continue;} if (debugon) {system.out.println ("ZE.GETNAME () =" ZE.GETNAME () "," "getSize () =" Ze.getsize ());} Int size = (int) Ze.getsize (); // -1 indicates the size unknown. 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 (nullpointers) {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 limit path name in the file, for example, not the class name in the package - the ZiPENTRY class in the java.util.zip package will be named "Java / UtiL / Zip / Zipentry, not "java.util.zip.zilentry". The last important part of the code is a simple test driver. This test driver is a simple application that receives JAR / ZIP file name and resource name. It tries to discover the resource file in the file, and then report the successful or failed message:
Public static void main (string [] args) throws ioException {if (args.length! = 2) {system.err.println ("USAGE: Java JarResources
"); 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 "). ") }}} // jarResources class end.
You have learned this class. An easy-to-use class that hides all the thorny issues that use the resource packaged in the JAR file.
Exercise Now you have a certain understanding of extracting resources from the file file, below is some instructions available to modify and extend the JarResources class:
All content is loaded at once during the construction, and the load is delayed. For large JAR files, there may be no enough memory to load all files during the construction. Not just a general reading method similar to getResource (), we also provide resources-specific reading methods -, for example, a getImage () method for returning the Java Image object, used to return the GetClass () method of the Java Class object () method () With the assistance of custom class loaders),,,,, If the JAR file is small enough, we can prepare all resources based on their extensions (.gif, .class, etc.). Some methods should provide information about a given JAR file itself (basically zipfile package), including: jar / zip's entry number; return all resource name ENUMERATOR; return to a specific entry length (and other attributes) Allow reading methods to prepare indexes, this is just a few examples. JarResources can be extended for use in applet. By using the applet parameters and the URLConnection class, you can download JAR content from the web, rather than open the file as a local file. In addition, we can extend this class into a custom Java content handler.
Summary If you have eager to know how to extract images from the JAR file, you have learned a method. With this new class provided by this skill, you can not only use the JAR file to process images, but also to extract any resources in the JAR file. Author Abtrue Arthur Choi is currently an IBM adviser programmer. He has served in several companies, including Samsung Network Laboratory and Mitre. The project he participated includes client / server system, distributed object computing, and network management. He used multiple languages in various operating system environments. He started programming with Fortran IV and COBOL in 1981. Later he turned to C and C , he has been working in Java for the last two years. His most interested Java application is a data warehouse in a wide area network and parallel processing and distributed processing (using agent-based programming). Reach Arthur's email address is Arthur.choi@javaworld.com. John Mitchell, I have been employees, consultants, now is the boss of their own company. In the past decade, the area he investment includes the development of frontier computer software, providing recommendations and training for other developers. His consulting includes Java technology, compilers, interpreters, web applications and Internet business, etc. John is one of the author of Making Sense of Java: a guide for managers and the rest of us, and published many articles in programming magazines. In addition to writing Java Tips columns for JavaWorld, he has paid a comp.lang.tcl.announce and comp.binaries.geos newsgroup. Reach John's email address is john.mitchell@javaworld.com.
Reference resource
This is a class file JarResources.java jarresources.java jars http://www.javasoft.com/guide/jdk/1.1/docs/guide/jar/index.html For more information on Java archive support, see "Java TIP 21: Use archive files to speted up applet loading "http://www.javaworld.com/javatips/jw-javatip21.html