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
| /** * 压缩多个文件夹中的所有文件到ZIP文件 * * @param sourceFolderPaths 要压缩的文件夹路径数组 * @param zipFilePath 输出的ZIP文件路径 * @param fileRenamer 一个函数,用于为每个文件指定新的名称(可以为null,表示不重命名) * @throws IOException 如果发生I/O错误 */ public static void compressFolders(Set<String> sourceFolderPaths, String zipFilePath, java.util.function.Function<String, String> fileRenamer) throws IOException { String parentPath = FileUtil.getParent(zipFilePath, 1); File filePath = new File(parentPath); if (!filePath.exists()) { filePath.mkdirs(); }
try (ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(zipFilePath))) { for (String sourceFolderPath : sourceFolderPaths) { Path sourceFolder = Paths.get(sourceFolderPath); if (!Files.isDirectory(sourceFolder)) { continue; }
// 为每个文件夹添加一个顶级目录(可选) String folderBaseName = sourceFolder.getFileName().toString();
Files.walk(sourceFolder) .filter(path -> !Files.isDirectory(path)) .forEach(path -> { try { // 计算相对路径 String relativePath = sourceFolder.relativize(path).toString();
// 应用重命名函数(如果提供) String entryName = (fileRenamer != null) ? fileRenamer.apply(relativePath) : relativePath;
// 如果需要为每个文件夹添加顶级目录 if (sourceFolderPaths.size() > 1) { entryName = folderBaseName + "/" + entryName; }
// 确保路径使用正斜杠(ZIP规范) entryName = entryName.replace(File.separatorChar, '/');
// 添加到ZIP文件 ZipEntry zipEntry = new ZipEntry(entryName); zos.putNextEntry(zipEntry);
// 写入文件内容 Files.copy(path, zos); zos.closeEntry(); } catch (IOException e) { throw new UncheckedIOException(e); } }); } } catch (UncheckedIOException e) { throw e.getCause(); } }
|