java apache.commons.compress Zip压缩

文章描述了一个Java方法,用于将多个文件和文件夹递归地压缩到指定的ZIP文件中,包括处理大文件和异常情况。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

@SneakyThrows
    public static void toZip(String srcFile, String zipFilePath)  {
        if(StringUtils.isEmpty(zipFilePath)){
            return;
        }
        List<String> pathList = new ArrayList<>();
        pathList.add(srcFile);
        toZip(pathList,zipFilePath);
    }

    /**
     *
     * @param largeFilePathList 被压缩的文件路径
     * @param zipFilePath zip文件输出目录一定要存在,否则会报错
     * @throws IOException
     */
    @SneakyThrows
    public static void toZip(List<String> largeFilePathList, String zipFilePath){
        try (ZipArchiveOutputStream zipOut = new ZipArchiveOutputStream(new FileOutputStream(new File(zipFilePath)))) {
            // 设置为使用ZIP64格式,支持大文件
            zipOut.setUseZip64(Zip64Mode.AsNeeded);
            for(String largeFilePath : largeFilePathList){
                File largeFile = new File(largeFilePath);
                if(!largeFile.exists()){
                    continue;
                }
                toZip(largeFile, zipOut, "");
            }
        }catch (Exception e){
            log.error("zipFile-----出现未知异常----->",e);
            throw new IOException("zipFile-----出现未知异常----->");
        }
    }

    private static void toZip(File file, ZipArchiveOutputStream zos, String base) throws IOException {
        if(file.isDirectory()) {
            File[] files = file.listFiles();
            if (Objects.isNull(files) || files.length <= 0) {
                return ;
            }
            for (File child : files) {
                toZip(child, zos, base + file.getName() + File.separator);
            }
        }else {
            ZipArchiveEntry entry = new ZipArchiveEntry(base + file.getName());
            entry.setSize(file.length());
            zos.putArchiveEntry(entry);
            byte[] buffer = new byte[1024 * 1024];
            FileInputStream fis = new FileInputStream(file);
            int len;
            while ((len = fis.read(buffer)) != -1) {
                zos.write(buffer, 0, len);
            }
            fis.close();
            zos.closeArchiveEntry();
        }
    }
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值