Unzipping a zip file and checking for data integrity

This post explains how to unzip a zip file and check whether data were correctly extracted.


package ZipDemo;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Enumeration;
import java.util.zip.CRC32;
import java.util.zip.CheckedInputStream;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;

public class ZipDemo6 {
    public static void main(String[] args) throws FileNotFoundException, IOException {
        String destination = "E:\\Projects\\JavaProjects\\JavaConcepts\\WorkFolder\\Folder1";
        try (ZipFile zipFile = new ZipFile("E:\\Projects\\JavaProjects\\JavaConcepts\\WorkFolder\\Folder1.zip")){
            File folder = new File(destination);
            folder.mkdir();
            Enumeration entries = zipFile.entries();
            for (Enumeration e = entries; e.hasMoreElements();) {
                ZipEntry zipEntry = e.nextElement();
                if(zipEntry.isDirectory()) {
                    File childFolder = new File(folder, zipEntry.getName());
                    childFolder.mkdir();
                } else {
                    try(FileOutputStream fos = new FileOutputStream(folder.getAbsolutePath() + "\\" + zipEntry.getName());
                    InputStream zis = zipFile.getInputStream(zipEntry);
                    CheckedInputStream checkedInputStream = new CheckedInputStream(zis, new CRC32());) {

                        byte[] data = new byte[1024];

                        int bytesRead = checkedInputStream.read(data);
                        while(bytesRead != -1) {
                            fos.write(data,0,bytesRead);
                            bytesRead = checkedInputStream.read(data);
                        }
                        if(zipEntry.getCrc() == checkedInputStream.getChecksum().getValue()) {
                            System.out.println("Verified");
                        } else {
                            System.out.println("Non Verified");
                        }
                        fos.flush();
                        fos.close();
                    }
                }
            }
        }
    }
}

Explanation

We have to use CheckedInputStream which computes the checksum when reading a file entry. Once reading a particular file entry is done, we can get the computed checksum by calling
checkedInputStream.getChecksum()

We can compare the checksum with the checksum stored with each entry in the zip file. We can retrieve the stored checksum by calling
zipEntry.getCrc()

And check whether they are same using the below code
if(zipEntry.getCrc() == checkedInputStream.getChecksum().getValue()) {
System.out.println(“Verified”);
} else {
System.out.println(“Non Verified”);
}

Leave a Reply