Skip to content

Java: Create Zip files

Creating a zip file in Java can be done using the java.util.zip package. Here’s an example of how you can create a zip file

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

public class ZipCreator {

    public static void main(String[] args) {
        String sourceFolderPath = "path/to/source/folder"; // Path to the folder you want to zip
        String zipFilePath = "path/to/output/zipfile.zip"; // Path to the output zip file
        
        zipFolder(sourceFolderPath, zipFilePath);
    }

    public static void zipFolder(String sourceFolderPath, String zipFilePath) {
        try {
            FileOutputStream fos = new FileOutputStream(zipFilePath);
            ZipOutputStream zos = new ZipOutputStream(fos);

            addFolderToZip(sourceFolderPath, sourceFolderPath, zos);

            zos.close();
            fos.close();
            System.out.println("Folder successfully compressed into Zip file.");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private static void addFolderToZip(String folderPath, String sourceFolderPath, ZipOutputStream zos) throws IOException {
        File folder = new File(folderPath);
        File[] files = folder.listFiles();

        for (File file : files) {
            if (file.isDirectory()) {
                addFolderToZip(file.getAbsolutePath(), sourceFolderPath, zos);
                continue;
            }

            String relativePath = file.getAbsolutePath().substring(sourceFolderPath.length() + 1);
            ZipEntry zipEntry = new ZipEntry(relativePath);
            zos.putNextEntry(zipEntry);

            FileInputStream fis = new FileInputStream(file);
            byte[] buffer = new byte[1024];
            int length;
            while ((length = fis.read(buffer)) > 0) {
                zos.write(buffer, 0, length);
            }

            zos.closeEntry();
            fis.close();
        }
    }
}

Replace "path/to/source/folder" with the path of the folder you want to zip, and "path/to/output/zipfile.zip" with the desired path and name for your output zip file. This code recursively zips all files and subdirectories within the specified folder.

Remember to handle exceptions properly when working with file operations in Java, as shown in the example above with try-catch blocks.

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Inline Feedbacks
View all comments