Recebi isso por email da lista JDC Tech Tips da SUN.
 

READING FILES FROM JAVA ARCHIVES (JARS)

Java archive (JAR) files are the standard way of packaging Java technology-based solutions. They allow a developer to package all relevant content (.class, image, sound, and support files) in a single file. The JAR format supports compression, authentication, and versioning, among many other features.

Getting files out of JAR files can be a tricky task, but it doesn't have to be. This tip shows you how to get a file out of a JAR file, by first getting a directory of files in the JAR file, and then pulling out a specific one.

If you are familiar with the popular ZIP format, JAR files aren't much different. JAR files provide a way of packaging multiple files into one, where each file may be compressed separately. What the JAR file adds is something called a manifest which allows a developer to provide additional information about the content. For example, the manifest can indicate which file in the JAR file to run to start an application, or the version of a library.

The Java 2 SDK, Standard Edition provides a jar tool that allows you to read and write JAR files from the console. However there might be times when you need to read and write JAR files from within your programs. (This tip will only cover reading JAR files from within a program.) The good news is that you can do this, and you don't have to worry about the decompression, because the library handles it for you. The classes you need are in the java.util.jar package. The main class here is JarFile which is a reference to the .jar file itself. Each individual file within the bigger file is referenced by a JarEntry.

To get started, you create a JarFile instance by passing the location to the constructor. This could be in the form of a String or a File:

    JarFile jarFile = new JarFile("thefile.jar");

or

    File file = new File("thefile.jar");
    JarFile jarFile = new JarFile(file);

There are other constructors for authentication support and marking the file for deletion. However those constructors will not be covered here.

After you have a reference to the JAR file, you can read the directory of its contents. The entries method of JarFile returns an Enumeration of all the entries. From each entry, you can then get its attributes from the manifest file, any certificate information, and any other information specific to the entry such as its name or size.

  Enumeration enum = jarFile.entries();
  while (enum.hasMoreElements()) {
    process(enum.nextElement());
  }

As previously mentioned, each individual entry is a JarEntry. This class has methods such as getName, getSize, and getCompressedSize.

Let's illustrate how to use these features in a program. The following program displays the name, size, and compressed size of the contents of a JAR file you specify. (This is similar to what the jar command does when you specify it with the "t" and "v" options.)

   import java.io.*;
   import java.util.*;
   import java.util.jar.*;

   public class JarDir {
     public static void main (String args[]) 
         throws IOException {
       if (args.length != 1) {
         System.out.println(
            "Please provide a JAR filename");
         System.exit(-1);
       }
       JarFile jarFile = new JarFile(args[0]);
       Enumeration enum = jarFile.entries();
       while (enum.hasMoreElements()) {
         process(enum.nextElement());
       }
     }

     private static void process(Object obj) {
       JarEntry entry = (JarEntry)obj;
       String name = entry.getName();
       long size = entry.getSize();
       long compressedSize = entry.getCompressedSize();
       System.out.println(
           name + "\t" + size + "\t" + compressedSize);
     }
   }

If you run the JarDir program with the jce.jar file that comes with J2SE 1.4.1, you should see output that looks something like this (with more files shown where the ... is):

META-INF/MANIFEST.MF    5315    1910
META-INF/4JCEJARS.SF    5368    1958
META-INF/4JCEJARS.DSA   2207    1503
META-INF/       0       2
javax/  0       0
javax/crypto/   0       0
javax/crypto/interfaces/        0       0
javax/crypto/interfaces/DHKey.class     209     185
javax/crypto/interfaces/DHPublicKey.class       265     215
javax/crypto/interfaces/DHPrivateKey.class      267     215
javax/crypto/interfaces/PBEKey.class    268     224
javax/crypto/SecretKey.class    167     155
...

Notice the META-INF lines at the start of the output. This is the manifest and security certificate information. The entries with a 0 size are not files, but rather directories.

To actually read a specific file from a JAR file, you must get the InputStream for the entry. This is different than the JarEntry. That's because the JarEntry only contains information about the entry, not the actual contents of that entry. This is similar to the distinction between File and FileInputStream. Accessing File never opens the file, it just reads the information about it from the directory. Here's how to get the InputStream for the entry:

   InputStream input = jarFile.getInputStream(entry);

After you have an input stream, you can just read it like any other stream. In the case of a text stream, remember to use a Reader to get characters from the stream. For byte-oriented streams such as image files, just read directly.

The following program demonstrates reading from a JAR file. Call the program with the name of a JAR file followed by the file name to read. The file to be read must have a text file type.

   import java.io.*;
   import java.util.jar.*;

   public class JarRead {
     public static void main (String args[]) 
         throws IOException {
       if (args.length != 2) {
         System.out.println(
           "Please provide a JAR filename and file to read");
         System.exit(-1);
       }
       JarFile jarFile = new JarFile(args[0]);
       JarEntry entry = jarFile.getJarEntry(args[1]);
       InputStream input = jarFile.getInputStream(entry);
       process(input);
     }

     private static void process(InputStream input) 
         throws IOException {
       InputStreamReader isr = 
      new InputStreamReader(input);
       BufferedReader reader = new BufferedReader(isr);
       String line;
       while ((line = reader.readLine()) != null) {
         System.out.println(line);
       }
       reader.close();
     }
   }

Suppose you had a text file named spider.txt in a JAR file named myfiles.jar. Suppose too that spider.txt contained the following text:

   The itsy bitsy spider 
   Ran up the water spout
   Down came the rain and
   Washed the spider out 

You could display the contents of the text file from the JAR file like this:

   java JarRead myfiles.jar spider.txt   

For more about JAR files, see the JAR file specification.

 

 

----- Original Message -----
Sent: Wednesday, February 19, 2003 8:46 AM
Subject: [java-list] Como ver arquivos jar

Ola caros colegas, como faco pra ver as classes dentro de um jar ???
 
E como faco pra gerar um jar , para ficar menor meu CLASSPATH ???
 
Obrigado ! ! !
 
jose antonio

Reply via email to