Java- extract / unzip a zip file - working code example

Extracting a ZIP archive in pure Java is easy with `java.util.zip.ZipInputStream`. In this tutorial, I'll walk you through a complete working method that reads every entry, recreates directories, and extracts files using modern best practices—including `try`-with-resources and `mkdirs()`. Copy the code below, drop in your `test.zip`, and run.
import java.io.*;
import java.util.zip.*;

public class UnzipTest {

    public static void unzipFile(File zipFile) throws IOException {
        // Destination folder next to the zip
        String destDir = zipFile.getParent() + File.separator + "unzipped";

        byte[] buffer = new byte[4096];

        try (ZipInputStream zis = new ZipInputStream(new FileInputStream(zipFile))) {

            ZipEntry entry;
            while ((entry = zis.getNextEntry()) != null) {
                File outputFile = new File(destDir, entry.getName());

                if (entry.isDirectory()) {
                    outputFile.mkdirs();
                } else {
                    // Ensure parent directories exist
                    outputFile.getParentFile().mkdirs();
                    try (FileOutputStream fos = new FileOutputStream(outputFile)) {
                        int len;
                        while ((len = zis.read(buffer)) > 0) {
                            fos.write(buffer, 0, len);
                        }
                    }
                }
                zis.closeEntry();
            }
        }
        System.out.println("Extracted to: " + destDir);
    }

    public static void main(String[] args) {
        try {
            unzipFile(new File("test.zip"));
            System.out.println("Success");
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println("Error - " + e.getMessage());
        }
    }
}

No comments :

Post a Comment

Your Comment and Question will help to make this blog better...