Friday, August 28, 2009

How to List Entries in ZipFile using Java

Java Utils package provides class ZipFile which is used to deal with ZipFile.

To retrieve entries in ZipFile, entries() method is used.
Ex. ZipFile zipFile = new ZipFile("CoreJava.zip");
zipFile.entries();

Once we have all entries available, we can enumerate using Enumerations.
Enumeration enumeration = zipFile.entries();
while(enumeration.hasMoreElements()){
System.out.println(enumeration.nextElement());
}

Java Program to List content of ZIP File :

package com.anuj.utils;
package com.anuj.utils;

import java.io.IOException;
import java.util.Enumeration;
import java.util.zip.ZipException;
import java.util.zip.ZipFile;

public class ListZipFiles {
 /**
  * @param args
  * @throws IOException
  */
 public static void main(String[] args) throws IOException {
   
  try {
   ZipFile zipFile = new ZipFile("CoreJava.zip");
   Enumeration enumeration = zipFile.entries();
   while(enumeration.hasMoreElements()){
    System.out.println(enumeration.nextElement());
   }
  } catch (ZipException ze) {
   System.out.println(ze.getMessage());
   System.out.println("Zip file may be corrupted.");
   System.exit(0);
  }
 }
}

No comments:

Post a Comment