How do I create checksum for a zip file?

This example demonstrate how to use CheckedOutputStream for creating a checksum of a zip file. Checksum can be used to detect whether a data was corrupted during a transmission process to a remote machine.

package org.kodejava.util.zip;

import java.io.*;
import java.util.Objects;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
import java.util.zip.CheckedOutputStream;
import java.util.zip.Adler32;

public class ZipWithChecksum {
    public static void main(String[] args) throws Exception {
        String target = "data-1.zip";

        try (FileOutputStream fos = new FileOutputStream(target);
             // An output stream that also maintains a checksum of the data
             // being written. The checksum can then be used to verify the
             // integrity of the output data.
             CheckedOutputStream checksum =
                     new CheckedOutputStream(fos, new Adler32())) {
            try (ZipOutputStream zos =
                         new ZipOutputStream(new BufferedOutputStream(checksum))) {

                int size;
                byte[] buffer = new byte[1024];

                // Get all text files on the working folder.
                File dir = new File(".");
                String[] files = dir.list((directory, name) -> name.endsWith(".txt"));

                for (String file : Objects.requireNonNull(files)) {
                    System.out.println("Compressing: " + file);

                    try (FileInputStream fis = new FileInputStream(file);
                         BufferedInputStream bis =
                                 new BufferedInputStream(fis, buffer.length)) {

                        // put a new ZipEntry in the ZipOutputStream
                        ZipEntry zipEntry = new ZipEntry(file);
                        zos.putNextEntry(zipEntry);

                        // read data to the end of the source file and write it
                        // to the zip output stream.
                        while ((size = bis.read(buffer, 0, buffer.length)) > 0) {
                            zos.write(buffer, 0, size);
                        }

                        zos.closeEntry();
                    }
                }
            }

            // Print out checksum value
            long value = checksum.getChecksum().getValue();
            System.out.println("Checksum   : " + value);
        }
    }
}

How do I decompress a zip file using ZipFile class?

In this example we use the java.util.zip.ZipFile class to decompress and extract a zip file.

package org.kodejava.util.zip;

import java.util.zip.ZipFile;
import java.util.zip.ZipEntry;
import java.util.Enumeration;
import java.io.*;

public class ZipFileUnzipDemo {
    public static void main(String[] args) throws Exception {
        String zipName = "data.zip";

        ZipFile zip = new ZipFile(zipName);
        Enumeration<? extends ZipEntry> enumeration = zip.entries();

        while (enumeration.hasMoreElements()) {
            ZipEntry zipEntry = enumeration.nextElement();
            System.out.println("Unzipping: " + zipEntry.getName());

            int size;
            byte[] buffer = new byte[2048];

            try (BufferedInputStream bis =
                         new BufferedInputStream(zip.getInputStream(zipEntry));
                 FileOutputStream fos =
                         new FileOutputStream(zipEntry.getName());
                 BufferedOutputStream bos =
                         new BufferedOutputStream(fos, buffer.length)) {

                while ((size = bis.read(buffer, 0, buffer.length)) != -1) {
                    bos.write(buffer, 0, size);
                }
                bos.flush();
            }
        }
    }
}

How do I decompress a zip file using ZipInputStream?

The code below shows how to decompress and extract files from a zip archive. In the example we use the java.util.zip.ZipInputStream class.

package org.kodejava.util.zip;

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

public class UnzipDemo {
    public static void main(String[] args) {
        String zipName = "data.zip";

        try (FileInputStream fis = new FileInputStream(zipName);
             ZipInputStream zis =
                 new ZipInputStream(new BufferedInputStream(fis))) {

            ZipEntry entry;

            // Read each entry from the ZipInputStream until no
            // more entry found indicated by a null return value
            // of the getNextEntry() method.
            while ((entry = zis.getNextEntry()) != null) {
                System.out.println("Unzipping: " + entry.getName());

                int size;
                byte[] buffer = new byte[2048];

                try (FileOutputStream fos =
                         new FileOutputStream(entry.getName());
                     BufferedOutputStream bos =
                         new BufferedOutputStream(fos, buffer.length)) {

                    while ((size = zis.read(buffer, 0, buffer.length)) != -1) {
                        bos.write(buffer, 0, size);
                    }
                    bos.flush();
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

How do I create a zip file?

package org.kodejava.util.zip;

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

public class ZippingFileExample {
    public static void main(String[] args) {
        String source = "data.txt";
        String target = "data.zip";

        try (ZipOutputStream zos = 
                 new ZipOutputStream(new FileOutputStream(target));
             InputStream is = 
                 ZippingFileExample.class.getResourceAsStream("/" + source)) {
            if (is != null) {
                // Put a new ZipEntry in the ZipOutputStream
                zos.putNextEntry(new ZipEntry(source));

                int size;
                byte[] buffer = new byte[1024];

                // Read data to the end of the source file and write it
                // to the zip output stream.
                while ((size = is.read(buffer, 0, buffer.length)) > 0) {
                    zos.write(buffer, 0, size);
                }

                zos.closeEntry();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

How do I read entries in a zip / compressed file?

package org.kodejava.util.zip;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.Enumeration;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;

public class ZipFileExample {
    public static void main(String[] args) {
        try {
            // Create an instance of ZipFile to read a zip file
            // called sample.zip
            ZipFile zip = new ZipFile(new File("data.zip"));

            // Here we start to iterate each entry inside
            // sample.zip
            for (Enumeration<?> e = zip.entries(); e.hasMoreElements(); ) {
                // Get ZipEntry which is a file or a directory
                ZipEntry entry = (ZipEntry) e.nextElement();

                // Get some information about the entry such as
                // file name, its size.
                System.out.println("File name: " + entry.getName()
                    + "; size: " + entry.getSize()
                    + "; compressed size: "
                    + entry.getCompressedSize());
                System.out.println();

                // Now we want to get the content of this entry.
                // Get the InputStream, we read through the input
                // stream until all the content is read.
                InputStream is = zip.getInputStream(entry);
                InputStreamReader isr = new InputStreamReader(is);

                char[] buffer = new char[1024];
                while (isr.read(buffer, 0, buffer.length) != -1) {
                    String s = new String(buffer);
                    // Here we just print out what is inside the
                    // buffer.
                    System.out.println(s.trim());
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}