How to unzip (.zip files) archived or compressed files in ZIP formats using Java?

We use winrar or winzip to unzip files in windows. I once wondered if I could write a java program to unpack .zip files and java.util.zip package was my answer. This core package of java is used to unzip (unpack or open) compressed files in ZIP formats.

How to unzip (.zip files) archived or compressed files in ZIP formats using Java?

This article is part of a tutorial.
Tutorial Index page - Java Compression and Decompression

Introduction

How to unzip (.zip files) archived or compressed files in ZIP formats using Java?

Before answering this question we first need to quickly remind ourselves what a ZIP file/format is.

"The ZIP file format is a data compression and archive format. A ZIP file contains one or more files that have been compressed to reduce file size, or stored as-is. The ZIP file format permits a number of compression algorithms but, as of 2009, the Deflate method continues to be dominant." - Wikipedia

Java SDK Package - java.util.zip

The Java SDK provides a dedicated package - java.util.zip of numerous classes for reading and writing the standard ZIP and GZIP file formats.

This packcage provides classes for reading and writing the standard ZIP and GZIP file formats. It also includes classes for compressing and decompressing data using the DEFLATE compression algorithm, which is used by the ZIP and GZIP file formats. Additionally, there are utility classes for computing the CRC-32 and Adler-32 checksums of arbitrary input streams.

This article will use two of the most basic classes offered by this package:

  • ZipFile - This class is used to read entries from a zip file.
  • ZipEntry - This class is used to represent a ZIP file entry.

Algorithm

With the above introduction lets dive straight into the algorithm we will employ to unZIP a ZIP file.

  1. Prepare the ZIP file for reading
  2. Get an enumeration of the ZIP file entries i.e. contents of the ZIP file
  3. For each ZIP entry
  • If ZIP entry is a directory

Create a directory with the ZIP entry's name

  • else if ZIP entry is a file

Create a file with the ZIP entry's name & write contents of the ZIP entry to that file

Feedback or Questions?

We welcome feedback and questions and will try our best to attend to it as quickly as possible!

Please note that you would have to register before you can post in our forums and this is purely to guard us from the spam-bots. Be assured that we do not send spam mails and our website registration only takes minutes.