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:

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

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
 1package com.firstfewlines;
 2
 3import org.apache.commons.compress.archivers.zip.ZipArchiveEntry;
 4import org.apache.commons.compress.archivers.zip.ZipFile;
 5
 6import java.io.File;
 7import java.io.FileOutputStream;
 8import java.io.InputStream;
 9import java.util.Enumeration;
10
11public class ZipSample {
12
13    public static void main(String [] argv) throws Exception {
14        System.out.println("Extracting Zip:");
15        extractFile(new File("D:\\test.zip"));
16    }
17
18    static void extractFile(File zipFile) throws Exception
19    {
20        byte[] buffer = new byte[4096];
21        ZipFile zf = new ZipFile(zipFile);
22
23        Enumeration<ZipArchiveEntry> entries = zf.getEntries();
24
25        while(entries.hasMoreElements())
26        {
27            ZipArchiveEntry ze = entries.nextElement();
28            String zefilename = ze.getName();
29
30            System.out.println("Extracting file: " + zefilename);
31            File extfile = new File(zefilename);
32
33            InputStream zis = zf.getInputStream(ze);
34            FileOutputStream fos = new FileOutputStream(extfile);
35            try {
36                int numBytes;
37                while ((numBytes = zis.read(buffer, 0, buffer.length)) != -1)
38                    fos.write(buffer, 0, numBytes);
39            }
40            finally {
41                fos.close();
42                zis.close();
43            }
44
45        }
46        zf.close();
47    }
48}

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

References:


comments powered by Disqus