How can I read .zip and .jar file using standard Java classes?

John Zukowski

The ZIP and JAR reading classes are found in the java.util.zip and java.util.jar packages respectively. The following demonstrates reading from a ZIP file, listing all the files in the zip and displaying the contents of the first file in the zip. JAR file reading is similar, just with different classes and having a manifest.


import java.util.zip.*;
import java.util.*;
import java.io.*;

public class ZipExample {
  public static void main(String args[]) {
    try {
      ZipFile zf = new ZipFile("the.zip");
      Enumeration entries = zf.entries();
      String first = null;
      while (entries.hasMoreElements()) {
        ZipEntry ze = (ZipEntry)entries.nextElement();
        System.out.println("Entry " + ze.getName());
        if (first == null) first = ze.getName();
      }
      ZipEntry ze = zf.getEntry(first);
      if (ze != null) {
        BufferedReader br = new BufferedReader(
          new InputStreamReader(zf.getInputStream(ze)));
        long size = ze.getSize();
        if (size > 0) {
          System.out.println(first + " Length is " + size);
          String line;
          while ((line = br.readLine()) != null) {
            System.out.println(line);
          }
          br.close();
        }
      }
    } catch(IOException e) { 
      e.printStackTrace();
    }
  }
}
0 Comments  (click to add your comment)
Comment and Contribute

 

 

 

 

 


(Maximum characters: 1200). You have 1200 characters left.

 

 

About | Sitemap | Contact