杜洪波
2025-06-18 466d488372f884883fa02cc3ca9877b073fe39c9
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
package com.product.system.backup.util;
 
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;
import java.util.Map;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
 
public class SystemBackupUtil {
 
    /**
     *     压缩文件到指定ZIP文件
     * @param file        被压缩文件
     * @param entryName    ZIP文件目录节点
     * @param zos        目标ZIP文件
     * @throws IOException
     */
    public static void addFileToZip(File file, String entryName, ZipOutputStream zos) throws IOException {
        try (FileInputStream fis = new FileInputStream(file)) {
            zos.putNextEntry(new ZipEntry(entryName));
            byte[] buffer = new byte[1024];
            int length;
            while ((length = fis.read(buffer)) >= 0) {
                zos.write(buffer, 0, length);
            }
            zos.closeEntry();
        }
    }
    
    /**
     *     压缩增量附件
     * @param groupFolderFile    增量文件夹,文件名
     * @param baseDir            被压缩文件总目录
     * @param outputZipPath        目标压缩文件
     * @throws IOException
     */
    public static void compressExistingFiles(Map<String, List<String>> groupFolderFile, String baseDir, ZipOutputStream zos) throws IOException {
        for (Map.Entry<String, List<String>> entry : groupFolderFile.entrySet()) {
            String folderName = entry.getKey(); // 文件夹名(如 20250611)
            List<String> files = entry.getValue(); // 该文件夹下的文件名列表
            Path folderPath = Paths.get(baseDir).resolve(folderName);
            for (String fileName : files) {
                Path filePath = folderPath.resolve(fileName);
                // 检查文件是否存在
                if (Files.exists(filePath) && !Files.isDirectory(filePath)) {
                    // 计算 ZIP 内的相对路径(如 "20250611/file1.txt")
                    ZipEntry zipEntry = new ZipEntry(
                        String.valueOf(folderName) + "/" + fileName
                    );
                    zos.putNextEntry(zipEntry);
 
                    // 写入文件内容到 ZIP
                    Files.copy(filePath, zos);
                    zos.closeEntry();
                } else {
                    System.err.println("文件不存在或不是文件: " + filePath);
                }
            }
        }
    }
}