How to compress all files in a folder in Java?

You can use the ZipOutputStream class in Java to compress all files in a folder. Here is an example code:

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

public class ZipFolder {

    public static void main(String[] args) {
        File folderToZip = new File("path/to/folder");
        File zipFile = new File("path/to/output.zip");

        try {
            FileOutputStream fos = new FileOutputStream(zipFile);
            ZipOutputStream zos = new ZipOutputStream(fos);

            zipFolder(folderToZip, folderToZip.getName(), zos);

            zos.close();
            fos.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private static void zipFolder(File folder, String parentFolderName, ZipOutputStream zos) throws IOException {
        for (File file : folder.listFiles()) {
            if (file.isDirectory()) {
                zipFolder(file, parentFolderName + "/" + file.getName(), zos);
            } else {
                FileInputStream fis = new FileInputStream(file);

                ZipEntry zipEntry = new ZipEntry(parentFolderName + "/" + file.getName());
                zos.putNextEntry(zipEntry);

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

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

In the example above, the first step is to specify the folder path to be compressed and the output zip file path. Then, the zipFolder method recursively traverses all files in the folder and adds them to the ZipOutputStream. Finally, close the stream to complete the compression process.

bannerAds