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.
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.
- Create the ZipFile object
- Get the ZipEntry of the file we want to read ( getEntry(String name) method )
- Get the input stream to read the file from ZipFile using the ZipEntry ( getInputStream(ZipEntry entry) method )
- Read the InputStream
3 comments on “Java Zip API: How to Read a Zip File Using Java”
You must log in to post a comment.