zip

List contents of zip file

In this example we shall show you how to get the list of the contents of a zip file, with ZipFile that is used to read entries from a zip file. To get the files that a zip file contains one should perform the following steps:

  • Create a new ZipFile and open it for reading.
  • Get the Enumeration of the ZipFile entries, with entries() API method of ZipFile and iterate through each one of them.
  • For each one of the entries, get its name, with getName() API method of ZipEntry.
  • Close the ZipFile, with close() API method of ZipFile,
  • as described in the code snippet below.

package com.javacodegeeks.snippets.core;

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

public class ListContentsOfZipFile {
	
	public static void main(String[] args) {
		
		ZipFile zipFile = null;

		try {
			
			// open a zip file for reading
			zipFile = new ZipFile("c:/archive.zip");

			// get an enumeration of the ZIP file entries
			Enumeration<? extends ZipEntry> e = zipFile.entries();

			while (e.hasMoreElements()) {
				
				ZipEntry entry = e.nextElement();

				// get the name of the entry
				String entryName = entry.getName();
				
				System.out.println("ZIP Entry: " + entryName);

			}

		}
		catch (IOException ioe) {
			System.out.println("Error opening zip file" + ioe);
		}
		 finally {
			 try {
				 if (zipFile!=null) {
					 zipFile.close();
				 }
			 }
			 catch (IOException ioe) {
					System.out.println("Error while closing zip file" + ioe);
			 }
		 }
		
	}

}

 
This was an example of how to get the list of the contents of a zip file in Java.

Ilias Tsagklis

Ilias is a software developer turned online entrepreneur. He is co-founder and Executive Editor at Java Code Geeks.
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Inline Feedbacks
View all comments
Back to top button