Java压缩文件夹

   /**
     * 压缩文件夹
     *
     * @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());
        }
    }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值