package com.taais.biz.utils;

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

/**
 * @author SukangLee
 * @version 1.0
 * @date 2024/9/20 01:28
 * @description
 */
public class ZipDirectory {

    public static void zipDirectory(File folder, String outputZip) {
        try {
            FileOutputStream fos = new FileOutputStream(outputZip);
            ZipOutputStream zos = new ZipOutputStream(fos);
            addFolderToZip("", folder, zos);
            zos.flush();
            zos.close();
            fos.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private static void addFolderToZip(String path, File srcFile, ZipOutputStream zos) throws IOException {
        File[] files = srcFile.listFiles();

        for (File file : files) {
            if (file.isDirectory()) {
                addFolderToZip(path + file.getName() + "/", file, zos);
            } else {
                byte[] buffer = new byte[1024];
                FileInputStream fis = new FileInputStream(file);
                zos.putNextEntry(new ZipEntry(path + file.getName()));

                int length;
                while ((length = fis.read(buffer)) > 0) {
                    zos.write(buffer, 0, length);
                }

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