Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

java
zip
communitycreator

How to create a ZIP file from an existing file in Java

abhilash

What is a ZIP file?

A ZIP file is a collection of one or more files and/or folders that have been compressed into a single file for easy transfer and compression.

ZIP a single file

We can follow the steps below to create a ZIP file from an existing file.

Here, we assume the name of the file to be compressed is file.txt, and the compressed file name is file.zip.

  1. Check if the file exists in the filesystem. If the file doesn’t exist, then return back with the message “File does not exist”.
  2. Create a FileOutputStream object for the ZIP file to be created.
  3. Create an object of the ZipOutputStream class. Pass the FileOutputStream object created in Step 2 as the parameter to the constructor.
  4. Create a FileInputStream object for the text file to be compressed.
  5. Create a ZipEntry object that takes the input text file name as a constructor parameter.

Each file in the ZIP file is represented by a ZipEntry (java.util.zip.ZipEntry). Hence, to read/write from a ZIP file, ZipEntry is used.

  1. Insert the ZipEntry object created in Step 5 into the ZipOutputStream object, via the putNextEntry method.
  2. Write the contents of the text file to the ZipOutputStream object via the write method.
  3. Once all the content is written, close the ZipEntry object.
  4. Close the stream objects if no more files are there to compress.

Note: Use try-with-resources to autoclose the stream objects.

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

public class Zip {
    public static void main(String[] args) throws IOException {
        String fileName = "file.txt";
        String zipFileName = "file.zip";

        if (!Files.isRegularFile(Path.of(fileName))) {
            System.err.println("Please provide an existing file.");
            return;
        }

        ZipOutputStream zipOutputStream = new ZipOutputStream(
                new FileOutputStream(zipFileName));
        FileInputStream fileInputStream = new FileInputStream(fileName);

        ZipEntry zipEntry = new ZipEntry(fileName);
        zipOutputStream.putNextEntry(zipEntry);

        byte[] buffer = new byte[1024];
        int length;
        while ((length = fileInputStream.read(buffer)) > 0) {
            zipOutputStream.write(buffer, 0, length);
        }
        zipOutputStream.closeEntry();
        zipOutputStream.close();
        fileInputStream.close();
    }
}

RELATED TAGS

java
zip
communitycreator
RELATED COURSES

View all Courses

Keep Exploring