Site icon

Create compress /zip file in java (ZipOutputStream class /example)

  1. Given the input files in java, create zip or compress files using ZipOutputStream class .
  2. Java framework has provided couple of classes to create a zip & compress file.
    • ZipOutputStream: ZipOutputStream class implements an output stream filter for writing files in ZIP file format.
    • ZipEntry: ZipEntry class represents a ZIP file entry.
      • e.g. If we want to zip file named “FirstFile.txt”, then ZipEntry of “FirstFile.txt” shall be created.

1. Create compressed/zip file in java (ZipOutputStream/example)

2. Create compressed /zip file in java (ZipOutputStream /example)

package org.learn;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

public class ZipFilesInJava {

    public static void main(String[] args) throws IOException {

        //Path of output zip file
        String outputZip = "C:\\ZipDirectory\\files.zip";

        //Contents to be zipped.
        List<File> files = Arrays.asList(
                new File("C:\\ZipDirectory\\FirstFile.txt"),
                new File("C:\\ZipDirectory\\SecondFile.txt"),
                new File("C:\\ZipDirectory\\ThirdFile.txt")
        );
        System.out.println("1. Zipping the contents of input directory");
        createZipFile(outputZip, files);
        System.out.println("2. Successfully zipped contents");


    }

    private static void createZipFile(String outputZip, List<File> listOfFiles)
            throws IOException {

        //Create zip file
        ZipOutputStream zipOutputStream = new ZipOutputStream(
                new FileOutputStream(outputZip));

        for (File file : listOfFiles) {

            String fileName = file.getName();

            //Read files
            FileInputStream readFile = new FileInputStream(file);

            //Create zip entry
            ZipEntry zipEntry = new ZipEntry(fileName);
            //Set zip entry
            zipOutputStream.putNextEntry(zipEntry);

            int readChar = -1;
            while ((readChar = readFile.read()) != -1) {
                zipOutputStream.write(readChar);
            }

            readFile.close();
            zipOutputStream.closeEntry();
            System.out.println("Zipping input file: "+fileName);
        }
        zipOutputStream.close();
    }
}

3. Example: Create of zip of input files in java

Fig: Zip files using ZipOutputStream

4. Output – Create compressed /zip file in java (ZipOutputStream /example)

1. Zipping the contents of input directory
Zipping input file: FirstFile.txt
Zipping input file: SecondFile.txt
Zipping input file: ThirdFile.txt
2. Successfully zipped contents
Exit mobile version