Friday 24 March 2017

Java: List contents of a zip file

By using ZipFile class, we can get all the files in a zip file.

Following snippet is used to get all the file names is a zip file.

ZipFile zipFile = new ZipFile(path)
for (ZipEntry entry : Collections.list(zipFile.entries())) {
         System.out.println(entry.getName());
}

Find the following complete working application.
package com.sample;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;

public class ZipFileUtil {

 /**
  * 
  * @param path
  *            specifies the absolute path of zip file
  * @return empty list if path is empty/null, or if any exception comes, else
  *         return list of file names in given zip file.
  */
 public static List<String> getZipFiles(String path) {
  if (path == null || path.isEmpty()) {
   return Collections.emptyList();
  }

  try (ZipFile zipFile = new ZipFile(path)) {
   List<String> fileNames = new ArrayList<>();

   for (ZipEntry entry : Collections.list(zipFile.entries())) {
    fileNames.add(entry.getName());
   }

   return fileNames;
  } catch (IOException e) {
   e.printStackTrace();
   return Collections.emptyList();
  }

 }


}

package com.sample;

import java.io.IOException;
import java.util.List;

public class Test {
 public static void main(String args[]) throws IOException {
  List<String> fileNames = ZipFileUtil.getZipFiles("C:\\Users\\Krishna\\Documents\\Project related\\sample.zip");
  
  for(String fileName : fileNames){
   System.out.println(fileName);
  }
 }
}


No comments:

Post a Comment