How do I unzip the contents of a zip file?
Author: Deron Eriksson
Description: This Java tutorial describes how to unzip the contents of a zip file.
Tutorial created using: Windows XP || JDK 1.5.0_09 || Eclipse Web Tools Platform 2.0 (Eclipse 3.3.0)

Page:    1 2 >

In another tutorial, we saw how we could use the package to display the contents of a zip file. This tutorial will examine how to extract the contents of a zip file using the package and a little basic File/Stream JavaSW code.

This tutorial will utilize the following project. The file is the zip file that we will unzip, and ExtractZipContents is the Java class that will extract the contents of the zip file and write them to the file system.

'testing' project

The contents of the file are shown below. We have:


We can double-check this by examining the contents of with WinZip: contents viewed in WinZip

The ExtractZipContents class is shown below. It creates a ZipFile object based on It then enumerates over the ZipEntry objects within the zip file. It displays the name, size, and compressed size of each ZipEntry object. If the name of the ZipEntry ends with a slash, it is a directory, and this directory gets created along with all other directories above it via file.mkdirs(). The 'continue' skips the rest of the code in the while loop and lets the while loop go to the next zip entry.

If the name doesn't end with a slash, then we check to see if the file created from the current ZipEntry name has a parent file, which would be a directory. If it has a parent, the parent directory is created along with any other higher directories via the file.mkdirs() call.

Following this, the ExtractZipContents class does some standard Java input stream/output stream code to read the contents of the current ZipEntry object and write the contents to the file that was created using the ZipEntry name.

package test;

import java.util.Enumeration;

public class ExtractZipContents {

	public static void main(String[] args) {

		try {
			ZipFile zipFile = new ZipFile("");
			Enumeration<?> enu = zipFile.entries();
			while (enu.hasMoreElements()) {
				ZipEntry zipEntry = (ZipEntry) enu.nextElement();

				String name = zipEntry.getName();
				long size = zipEntry.getSize();
				long compressedSize = zipEntry.getCompressedSize();
				System.out.printf("name: %-20s | size: %6d | compressed size: %6d\n", 
						name, size, compressedSize);

				File file = new File(name);
				if (name.endsWith("/")) {

				File parent = file.getParentFile();
				if (parent != null) {

				InputStream is = zipFile.getInputStream(zipEntry);
				FileOutputStream fos = new FileOutputStream(file);
				byte[] bytes = new byte[1024];
				int length;
				while ((length = >= 0) {
					fos.write(bytes, 0, length);

		} catch (IOException e) {


(Continued on page 2)

Page:    1 2 >