How To Unzip File Using Java – Simple Tutorial

This tutorial is intended to show how Java programming language can be used to unzip a zip file. This program currently unzips a .zip extension.

Here are some features that I would like to highlight:

  • You can hard code the zip file location and destination extraction location and then run the program.
  • Alternately, you can pass these as an argument from the console.
  • If you pass the parameters from the console, hard coded parameters will be discarded.
  • This program does not maintain the folder structure.
  • It unzips all the files into a given destination directory.
  • You can tweak this program to unzip the file to the proper directory structures.
  • This file unzipping tutorial uses standard Java API.
  • You are free to modify and distribute this source code. Please honor my work by attributing back to my blog.

package com.kushal.utilities;

import java.io.*;
import java.util.*;
import java.util.zip.*;

public class MyUnzipUtil {

	public static final void main(String[] args) {
		/**
		 * Initialize the default parameters
		 */
		String zipFileName = "C:/myFolder/myZip.zip";
		String directoryToExtractTo = "C:/myFolder/unzipped/";

		/**
		 * Check if the arguments are passed from console.
		 * If so, we will discard the defalt parameters.
		 */

		if (args.length != 2) {
			System.err.println("Usage: MyUnzipUtil zipfile unzipLocation");
			System.err.println("...Using The Hardcoded Zip Location");
		} else {
			zipFileName = args[0];
			directoryToExtractTo = args[1];
		}

		/**
		 * Call the unzip method
		 */
		unzipMyZip(zipFileName, directoryToExtractTo);

	}

	/**
	 * This method
	 * --Reads an input stream
	 * --Writes the value to the output stream
	 * --Uses 1KB buffer.
	 */
	public static final void writeFile(InputStream in, OutputStream out)
			throws IOException {
		byte[] buffer = new byte[1024];
		int len;

		while ((len = in.read(buffer)) >= 0)
			out.write(buffer, 0, len);

		in.close();
		out.close();
	}

	public static void unzipMyZip(String zipFileName,
			String directoryToExtractTo) {
		Enumeration entriesEnum;
		ZipFile zipFile;
		try {
			zipFile = new ZipFile(zipFileName);
			entriesEnum = zipFile.entries();

			File directory= new File(directoryToExtractTo);

			/**
			 * Check if the directory to extract to exists
			 */
			if(!directory.exists())
			{
				/**
				 * If not, create a new one.
				 */
				new File(directoryToExtractTo).mkdir();
				System.err.println("...Directory Created -"+directoryToExtractTo);
			}
			while (entriesEnum.hasMoreElements()) {
				try {
					ZipEntry entry = (ZipEntry) entriesEnum.nextElement();

					if (entry.isDirectory()) {
						/**
						 * Currently not unzipping the directory structure.
						 * All the files will be unzipped in a Directory
						 *
						 **/
					} else {

						System.err.println("Extracting file: "
								+ entry.getName());
						/**
						 * The following logic will just extract the file name
						 * and discard the directory
						 */
						int index = 0;
						String name = entry.getName();
						index = entry.getName().lastIndexOf("/");
						if (index > 0 && index != name.length())
							name = entry.getName().substring(index + 1);

						System.out.println(name);

						writeFile(zipFile.getInputStream(entry),
								new BufferedOutputStream(new FileOutputStream(
										directoryToExtractTo + name)));
					}
				} catch (Exception e) {
					e.printStackTrace();
				}
			}

			zipFile.close();
		} catch (IOException ioe) {
			System.err.println("Some Exception Occurred:");
			ioe.printStackTrace();
			return;
		}
	}

}

Listing The Content Of Zip File With Zip Information In Java

The main objective of this tutorial is to show how to list  the content of a zip file along with zipping information. The program shows you:

  • How to iterate through the list of content of a zip file
  • How to get the name of the individual zip entry
  • How to get the compressed file size of an individual zip entry
  • How to get the uncompressed file size of an individual zip entry
  • How to obtain the CRC information of a zip entry
  • How to convert the long CRC information into hex format
  • How to obtain the comments of the individual zip entry.
  • Also note that since this tutorial tells you how to get the compressed file size and uncompressed file size, you can calculate the zip ratio yourself.
/**
 * @author Kushal Paudyal
 * www.sanjaal.com/java
 * Last Modified On 05-15-2009
 */
package com.kushal.utils;

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

/**
 * Demonstrates the ability to display the contents of a zip file Also
 * demonstrates how to get the zip info like compressed size, CRC etc.
 */
public class ZipContentDisplay {

	/**
	 * This method takes the zipfile name input parameter Then lists the content
	 * of the zip file.
	 */
	public static void listContentsOfZipFile(String zipFileName) {

		try {
			ZipFile myZipFile = new ZipFile(zipFileName);
			Enumeration zipEntries = myZipFile.entries();

			ZipEntry zipEntry = null;

			while (zipEntries.hasMoreElements()) {
				zipEntry = (ZipEntry) zipEntries.nextElement();
				System.out.println(zipEntry.getName());
			}

		} catch (IOException ex) {
			ex.printStackTrace();
		}

	}

	public static void listContentsOfZipFileWithInfo(String zipFileName) {

		try {
			ZipFile myZipFile = new ZipFile(zipFileName);
			Enumeration zipEntries = myZipFile.entries();

			ZipEntry zipEntry = null;

			while (zipEntries.hasMoreElements()) {
				zipEntry = (ZipEntry) zipEntries.nextElement();
				/**
				 * Get the file name
				 */
				String nameOfEntry = zipEntry.getName();
				/**
				 * Get Compressed File Size
				 */
				long compressedSizeOfEntry = zipEntry.getCompressedSize();
				/**
				 * Get Uncompressed file size
				 */
				long uncompressedSizeOfEntry = zipEntry.getSize();
				/**
				 * Get the CRC Code. Note that we have converted to hex.
				 */
				String crc = Long.toHexString(zipEntry.getCrc());
				/**
				 * Get the comment for the zip entry
				 */
				String comment = zipEntry.getComment();

				/**
				 * Display the result
				 */
				System.out.println("FileName: " + nameOfEntry
						+ "nCompressed Size(B): " + compressedSizeOfEntry
						+ "nOriginal Size(B): " + uncompressedSizeOfEntry
						+ "nCRC :" + crc + "nComments: " + comment);
				System.out.println("***");
			}

		} catch (IOException ex) {
			ex.printStackTrace();
		}

	}

	public static void main(String[] args) {

		String zipFileName = "C:/Temp/abc.zip";
		System.out.println("***Zip Content Display (File Names Only)***n");
		listContentsOfZipFile(zipFileName);

		System.out
				.println("nn***Zip Content Display (Detailed Information)***n");
		listContentsOfZipFileWithInfo(zipFileName);

	}
}

———————————————
Sample Output of this program (depends on your input zip file)

***Zip Content Display (File Names Only)***

abc/
abc/20090511_Files/
abc/20090511_Files/continuum.txt
abc/20090511_Files/custtemp.txt
abc/20090511_Files/depdoc.txt
abc/20090511_Files/librarylog.txt
abc/20090511_Files/logtemp.txt
abc/20090511_Files/sfmlog.txt

***Zip Content Display (Detailed Information)***

FileName: abc/
Compressed Size(B): 0
Original Size(B): 0
CRC :0
Comments: null
***
FileName: abc/20090511_Files/
Compressed Size(B): 0
Original Size(B): 0
CRC :0
Comments: null
***
FileName: abc/20090511_Files/continuum.txt
Compressed Size(B): 592
Original Size(B): 1568
CRC :36bc742
Comments: null
***
FileName: abc/20090511_Files/custtemp.txt
Compressed Size(B): 808
Original Size(B): 2052
CRC :ce0100bb
Comments: null
***
FileName: abc/20090511_Files/depdoc.txt
Compressed Size(B): 230
Original Size(B): 330
CRC :adad0544
Comments: null
***
FileName: abc/20090511_Files/librarylog.txt
Compressed Size(B): 210
Original Size(B): 491
CRC :2b1bab39
Comments: null
***
FileName: abc/20090511_Files/logtemp.txt
Compressed Size(B): 93
Original Size(B): 257
CRC :7e89e401
Comments: null
***
FileName: abc/20090511_Files/sfmlog.txt
Compressed Size(B): 2142
Original Size(B): 7763
CRC :f2931100
Comments: null
***

———————————————–
The following is the snapshot of the zip file as seen through winzip application: