Extract files from Zip archive in Java

There are few open source libraries available to extract files from Zip archive. Apache common compress is one of the popular library. We can use gradle to resolve the dependency of Apache common compress. For this, we have to make an entry under dependency in build.gradle like this:

dependencies {
    compile 'org.apache.commons:commons-compress:1.10'
}


To run this sample make sure to update your path of the zip file. The extracted files would be under current folder.

Now let us see the source code:

1. ZipSample.java
package com.firstfewlines;

import org.apache.commons.compress.archivers.zip.ZipArchiveEntry;
import org.apache.commons.compress.archivers.zip.ZipFile;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.util.Enumeration;

public class ZipSample {

    public static void main(String [] argv) throws Exception {
        System.out.println("Extracting Zip:");
        extractFile(new File("D:\\test.zip"));
    }

    static void extractFile(File zipFile) throws Exception
    {
        byte[] buffer = new byte[4096];
        ZipFile zf = new ZipFile(zipFile);

        Enumeration<ZipArchiveEntry> entries = zf.getEntries();

        while(entries.hasMoreElements())
        {
            ZipArchiveEntry ze = entries.nextElement();
            String zefilename = ze.getName();

            System.out.println("Extracting file: " + zefilename);
            File extfile = new File(zefilename);

            InputStream zis = zf.getInputStream(ze);
            FileOutputStream fos = new FileOutputStream(extfile);
            try {
                int numBytes;
                while ((numBytes = zis.read(buffer, 0, buffer.length)) != -1)
                    fos.write(buffer, 0, numBytes);
            }
            finally {
                fos.close();
                zis.close();
            }

        }
        zf.close();
    }
}


If you want to extract a single file or some specified files, you can do this by implementing a filter around ze.getName(); like:
while(entries.hasMoreElements())
{
    ZipArchiveEntry ze = entries.nextElement();
    String zefilename = ze.getName();
    if(!zefilename.equals(myfile))
        continue;
    . . . .


References:


Hansaraj avatar
About Hansaraj
Hansaraj is a Software Engineer experienced in Java, Groovy, JavaScript, SQL, C#, C++
comments powered by Disqus