Share on Google+Share on Google+

How to extract zip file in java.

In this tutorial you will see how to extracting the zip file.

How to extract zip file in java.

In this Example, we will discuss how to extract a ZIP file. We will use ZipInputStream class for creating input stream that take input from ZIP file. The ZipInputStream class is available in package.

With the help of example code, we can extract given file. The ZipInputStream class will create a input stream and read entry from given Zip file. The getNextEntry method of ZipInputStream class is used to read next ZIP file entry and put the stream at the beginning of the entry data, and the getName method of ZipEntry class return the name of associated entry. The write( byte b, int offset, int length) method of FileOutputStream class is used to write array of bytes..

About ZIPOutputStream API:

The class extends class. It provides following methods:

Return Type Method Description 
void close() The close() is use to close all associated  stream.
void closeEntry() The closeEntry() method close currently associated stream and put input stream to read next entry..
createZipEntry() The createZipEntry() method  create  new object for given entry name.
zipentry getNextEntry() The getNextEntry() method read next ZIP file entry and put  stream at the beginning of the entry data.
int read( byte b, int off, int len ) The read (.....) method read from associated  ZIP entry  into  array of bytes.
long skip( int n) Function skip specified number from input stream.



public class ExtractZipFile {
  public static void main(String[] argsthrows Exception {
    String fName = "";
    byte[] buf = new byte[1024];
    ZipInputStream zinstream = new ZipInputStream(
        new FileInputStream(fName));
    ZipEntry zentry = zinstream.getNextEntry();
    System.out.println("Name of current Zip Entry : " + zentry + "\n");
    while (zentry != null) {
      String entryName = zentry.getName();
      System.out.println("Name of  Zip Entry : " + entryName);
      FileOutputStream outstream = new FileOutputStream(entryName);
      int n;

      while ((n =, 01024)) > -1) {
        outstream.write(buf, 0, n);

      System.out.println("Successfully Extracted File Name : "
          + entryName);

      zentry = zinstream.getNextEntry();

Following is the output if you run the application:

C:\>java ExtractZipFile
Name of current Zip Entry : testfile2.txt
Name of Zip Entry : testfile2.txt
Successfully Extracted File Name : testfile2.txt
Name of Zip Entry : testfeli1.txt
Successfully Extracted File Name : testfeli1.txt

Download this code



Posted on: July 13, 2010 If you enjoyed this post then why not add us on Google+? Add us to your Circles

Share this Tutorial Follow us on Twitter, or add us on Facebook or Google Plus to keep you updated with the recent trends of Java and other open source platforms.


Advertisement null