Home » Core Java » util » zip » List contents of zip file

About Ilias Tsagklis

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

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.

Do you want to know how to develop your skillset to become a Java Rockstar?

Subscribe to our newsletter to start Rocking right now!

To get you started we give you our best selling eBooks for FREE!

 

1. JPA Mini Book

2. JVM Troubleshooting Guide

3. JUnit Tutorial for Unit Testing

4. Java Annotations Tutorial

5. Java Interview Questions

6. Spring Interview Questions

7. Android UI Design

 

and many more ....

 

Receive Java & Developer job alerts in your Area

 

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