Wednesday, August 11, 2010

How to read a zip file in Java?

This is not a basic tutorial but I just learned it, so I gonna show you how to write simple command line program to read content of zip file.

ZIP archives store one or more files in compressed format. Each ZIP archive has a header with information such as the name of the file and the compression method that was used.

In Java, ZipInputStream class use to read zip archives. To read zip file content one must check each individual entry in the zip file. The getNextEntry() method returns an object of type ZipEntry that describes zip entry. The read method of the ZipInputStream is modified to return -1 at the end of the current entry (instead of just at the end of the ZIP file). You must call closeEntry() method to read the next entry.

Here is my demonstration code I written.

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.zip.*;
import java.util.zip.ZipInputStream;


public class Main
{
  public static void main(String[] args) throws Exception
  {
      String file = "D:\\kiss.zip";
      try
      {
          FileInputStream fis = new FileInputStream(file);
          ZipInputStream zis = new ZipInputStream(fis);
          ZipEntry ze = null;
          while((ze = zis.getNextEntry()) != null)
          {
              System.out.println(ze.getName());
              zis.closeEntry();
          }
          zis.close();
      }
      catch(FileNotFoundException e)
      {
          System.out.println(e);
      }
      catch(IOException e)
      {
          System.out.println(e);
      }
        
  }
}

The ZIP input stream throws a ZipException when there is an error in reading a ZIP file. Normally this error occurs when the ZIP file has been corrupted.

No comments:

Post a Comment