RaKasUniverse.info

I still don't know why I registered this domain!

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

with 3 comments

Java API give a very simple set of classes to deal with zip files in its java.util.zip 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 —————-
Name: BlockedQueueTestCase.java
Size: 2348
CompSize: 956
————— Zip Entry —————-
Name: CEx.java
Size: 44
CompSize: 44
————— Zip Entry —————-
Name: CmdInput.java
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

Enjoy!

/Rakhitha

Related posts:

  1. Java Zip API: How to Create a Zip File Using Java
  2. Java Core API: Introduction to Java Reflections
  3. Fun with Java Reflections: Access Private Member Fields/Methods of other Classes

Written by Rakhitha

June 11th, 2010 at 6:52 pm

Posted in Java Stuff

Tagged with , , , ,

3 Responses to 'Java Zip API: How to Read a Zip File Using Java'

Subscribe to comments with RSS or TrackBack to 'Java Zip API: How to Read a Zip File Using Java'.

  1. Nice article. Very informative.

    Kanishka Dilshan

    11 Jun 10 at 8:37 PM

  2. Thanks Kanishka!

    Rakhitha

    11 Jun 10 at 10:14 PM

  3. [...] 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 [...]

Leave a Reply