View RSS Feed

My Java Tips

How To List Contents Of A JAR File In A Java Program

Rate this Entry
by , 11-08-2011 at 06:35 PM (2773 Views)
"jar" command line tool is used to create or list contents of a jar file. In a Java Program it is also possible to edit contents of a jar file. In "java.util.jar" package there are five ways to create a JAR file using JarFile.
Java Code:
    JarFile(File file) .
    JarFile(File file, boolean verify) .
    JarFile(File file, boolean verify, int mode) .
    JarFile(String name) .
    JarFile(String name, boolean verify) .
The default is to verify the file when "verify" flag is not specified. The mode setting is created with the help of two class constants "OPEN_READ" or "OPEN_READ | OPEN_DELETE". If "OPEN_DELETE" is set, the file is flagged for deletion by the system.
There are two key classes of the API.




JarFile.
JarEntry.

The JarFile class provides a reference to the whole JAR file, While the
JarEntry class points to each of the files contained within the JAR.

A Simple Example of using JarFile:
Java Code:
JarFile jar = new JarFile ("myjar.jar");
After getting a reference to a JAR file, list of Entries can be obtained with the help of "entries" method. This method returns an Enumeration of JarEntry objects. For each JarEntry object, Specific information about the entry can be obtained by API (eg. "getSize () "method). It is important that most of the methods are inherited from the parent "ZipEntry" class.

Run the following program to list contents of a "Jar" file. It takes name of jar/zip file as command line argument and list contents of jar files.

Java Code:
  import java.io.*;

   import java.util.*;

   import java.util.jar.*;

public class ShowJarContents {

     public static void main(String args[]) {

       for (int count=0, n=args.length; count

         try {

           showJar(args[count]);

         } catch (IOException e) {

           System.err.println("Errors In  reading: " + args[count]);

         }

       }

     }

private static void showJar(String name)

             throws IOException {

       System.out.println("Jar: " + name);

       JarFile jar = new JarFile(name);

       Enumeration e = jar.entries();

       while (e.hasMoreElements()) {

         listInfo((JarEntry)e.nextElement());

       }

       System.out.println();

     }

private static void listInfo(JarEntry entry) {

       System.out.println("n" + entry.getName());

    }

   }

Submit "How To List Contents Of A JAR  File In A Java Program" to Facebook Submit "How To List Contents Of A JAR  File In A Java Program" to Digg Submit "How To List Contents Of A JAR  File In A Java Program" to del.icio.us Submit "How To List Contents Of A JAR  File In A Java Program" to StumbleUpon Submit "How To List Contents Of A JAR  File In A Java Program" to Google

Tags: jatfile Add / Edit Tags
Categories
Java SE

Comments