package com.bonus.common.biz.config;

import com.bonus.common.biz.domain.FileInfo;

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

/**
 * 文件压缩工具类
 * @Author ma_sh
 * @create 2024/12/27 15:56
 */
public class FileCompressor {

    /**
     * 将多个文件压缩成ZIP文件
     * @param files 要压缩的文件列表
     * @param zipFilePath 目标ZIP文件路径
     * @throws IOException
     */
    public static void zipFiles(List<FileInfo> files, String zipFilePath) throws IOException {
        try (FileOutputStream fos = new FileOutputStream(zipFilePath);
             ZipOutputStream zipOut = new ZipOutputStream(fos)) {

            // 遍历每个文件
            for (FileInfo fileInfo : files) {
                File file = new File(fileInfo.getFilePath());
                // 确保文件存在
                if (!file.exists()) {
                    throw new FileNotFoundException("File not found: " + fileInfo.getFilePath());
                }
                // 添加文件到ZIP
                try (FileInputStream fis = new FileInputStream(file)) {
                    ZipEntry zipEntry = new ZipEntry(fileInfo.getFileName());
                    zipOut.putNextEntry(zipEntry);
                    // 将文件内容写入ZIP文件
                    byte[] bytes = new byte[1024];
                    int length;
                    while ((length = fis.read(bytes)) >= 0) {
                        zipOut.write(bytes, 0, length);
                    }
                    zipOut.closeEntry();
                }
            }
        }
    }
}
