How to Decompress Files from ZIP File in Java


In this example we will show the method to decompress files from a ZIP file in Java.

Source Code

package com.beginner.examples;

import java.io.*;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;

public class FileOperator28Example { 
	public static void main(String[] args) throws IOException{
        
        File path = new File("example.zip");
        String parentPath = path.getParent();
        ZipInputStream zis = new ZipInputStream(new FileInputStream(path));
        unzip(zis,parentPath);
        System.out.println("Done!");
    }
	private static void unzip(ZipInputStream zis,String parentPath) throws IOException {
        ZipEntry entry = zis.getNextEntry();
        if (entry != null) 
        {
            File file = new File(parentPath + File.separator + entry.getName());
            if (file.isDirectory())
            {
                if (!file.exists())
                {
                    file.mkdirs();
                }
                unzip(zis,parentPath);
            } 
            else 
            {
            	int len;
            	File parentFile = file.getParentFile();
                if (parentFile != null && !parentFile.exists())
                {
                    parentFile.mkdirs();
                }
                FileOutputStream out = new FileOutputStream(file);
                byte[] buf = new byte[1024];
                while ((len = zis.read(buf)) != -1) 
                {
                    out.write(buf, 0, len);
                }
                out.flush();
                out.close();
                zis.closeEntry();
                unzip(zis,parentPath);
            }
        }
    }
}

Output:

Done!

References

Imported packages in Java documentation:

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments