/**
* 压缩文件夹
*
* @param sourceDir 源文件夹路径
* @param zipPath 压缩文件路径
* @throws IOException
*/
private void zipFolder(String sourceDir, String zipPath) throws IOException {
Path sourcePath = Paths.get(sourceDir).toAbsolutePath();
// 确保源目录存在
if (!Files.exists(sourcePath) || !Files.isDirectory(sourcePath)) {
throw new ServiceException("源目录不存在或不是目录: " + sourceDir);
}
// "jar:file:" 固定写法,基于本地文件的 JAR/ZIP 存档
URI zipUri = URI.create("jar:file:" + zipPath.replace("\\", "/"));
Map<String, String> env = new HashMap<>();
env.put("create", "true");
// 确保支持中文文件名
env.put("encoding", "UTF-8");
try (FileSystem zipFs = FileSystems.newFileSystem(zipUri, env)) {
// 获取ZIP文件系统的根路径
Path rootInZip = zipFs.getPath("/");
// 遍历源目录
Files.walk(sourcePath)
.forEach(source -> {
try {
// 计算相对路径
Path relative = sourcePath.relativize(source);
if (relative.toString().isEmpty()) {
return; // 跳过根目录自身
}
Path dest = rootInZip.resolve(relative.toString());
if (Files.isDirectory(source)) {
// 创建目录
Files.createDirectories(dest);
} else {
// 复制文件
Files.copy(source, dest, StandardCopyOption.REPLACE_EXISTING);
}
} catch (Exception e) {
throw new ServiceException("无法压缩文件: " + source);
}
});
} catch (UncheckedIOException e) {
throw new ServiceException("压缩文件失败: " + e.getCause().getMessage());
} catch (ProviderNotFoundException e) {
throw new ServiceException("ZIP文件系统提供程序不可用,请检查JDK安装");
} catch (FileSystemAlreadyExistsException e) {
throw new ServiceException("ZIP文件已存在: " + zipPath);
} catch (Exception e) {
throw new ServiceException("压缩包生成失败: " + e.getMessage());
}
}
Java压缩文件夹
于 2025-07-08 16:43:38 首次发布