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);
|
}
|
}
|
}
|
}
|
}
|