Java 批量压缩文件,真正压缩多级文件

实际上,有很多相关的博客,但我测试了很多都 会出现两个问题,为避免新手踩坑而写

问题:

1、压缩完成后出现没有关闭流的现象(循环分别创建流对象未关闭导致)

2、压缩多级目录失效,只压缩部分文件(递归导致创建出多个压缩输出流对象)

 

解决如下:
 


    /**
     * 压缩多文件
     *
     * @param files    多个文件
     * @param basePath 压缩文件内的相对路径
     * @param zipFile  压缩文件
     * @throws IOException 异常
     */
    public static void zip(File[] files, String basePath, File zipFile) throws IOException {
        if (files == null || files.length == 0) return;

        FileOutputStream fos = new FileOutputStream(zipFile);
        ZipOutputStream zos = new ZipOutputStream(fos);
        try {
            procesZip(zos, files, basePath);
        } finally {
            closeStream(zos, fos); //关闭压缩流,输出流
        }

    }

    /**
     * 处理压缩,该部分抽离出来主要是为了保证 压缩输出流 不会多创建
     *
     * @param zos      压缩输出流
     * @param files    文件数组
     * @param basePath 压缩文件内的相对路径
     * @throws IOException 异常
     */
    private static void procesZip(ZipOutputStream zos, File[] files, String basePath) throws IOException {
        int count;// 数目
        final byte[] buffer = new byte[2048]; //缓冲
        for (File file : files) {
            if (file.isDirectory()) {
                procesZip(zos, file.listFiles(), basePath + File.separator + file.getName());// 递归
                continue;
            }

            zos.putNextEntry(new ZipEntry(basePath + File.separator + file.getName()));// 加入
            FileInputStream fis = new FileInputStream(file);// 输入

            // 读取
            while ((count = fis.read(buffer, 0, buffer.length)) != -1) {
                zos.write(buffer, 0, count);// 写入
            }

            zos.closeEntry();// 释放资源
            fis.close(); //关闭输入流
        }
    }



    /**
     * 关闭流
     *
     * @param closeables 不定长数组 流对象
     */
    public static void closeStream(Closeable... closeables) {
        for (Closeable closeable : closeables) {
            if (closeable != null) {
                try {
                    closeable.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

 

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 3
    评论
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值