Java Zip API: How to Read a Zip File Using Java

June 11, 2010 | By Rakhitha | Filed in: Java Stuff.

Java API give a very simple set of classes to deal with zip files in its package. I am just going to show how to access the content of a zip file using these classes. Basically in java point of view a zip file is a collection of zip entries. you just select the zip entry that you like to read and extract its content using an InputStream. However this API do not support handling of password protected zip files.

In the following example I am simply listing the content inside the zip file using a ZipFile instance and ZipEntry objects.

Sample Output:
————— Zip Entry —————-
Size: 2348
CompSize: 956
————— Zip Entry —————-
Size: 44
CompSize: 44
————— Zip Entry —————-
Size: 322
CompSize: 181

In above figure there is only two lines that are really doing the work (Line 9 and 11). Rest is for displaying the content. I am sure you can figure out what is happening in the code without me trying to explain.

Apart from entries method in ZipFile class. There is another method named getEntry if you want to get the zip entry of a specific file inside the zip file by its name. For more details please take a look at the API documentation of ZipFile class and ZipEntry class.

Above example simply listed the files inside zip file. Following example is on how to read the content of a file inside the zip file. Which is carouse very simple if you have already read the documentation of ZipFile class.

Following are the steps.

  1. Create the ZipFile object
  2. Get the ZipEntry of the file we want to read ( getEntry(String name) method )
  3. Get the input stream to read the file from ZipFile using the ZipEntry ( getInputStream(ZipEntry entry) method )
  4. Read the InputStream



Tags: , , , ,

3 comments on “Java Zip API: How to Read a Zip File Using Java

  1. Nice article. Very informative.

  2. […] is a follow-up to my earlier post “Java Zip API: How to Read a Zip File Using Java“. This time it’s about how to create a zip file using Java. This is even simpler than […]