java多文件打包压缩工具类实现

概述:项目中有个多文件打包下载的需求,需要实现一个多文件打包的工具类,工具类基于jdk1.8的API。

我的需求:如下图

 

工具类实现:

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
import static org.springframework.util.StreamUtils.BUFFER_SIZE;

/**
 * Author: liujian
 */

public  class  ZipUtil {
    private static final Logger log = LoggerFactory.getLogger(ZipUtil.class);

    public static void toZip(List<File> srcFiles, File zipFile) {
        long start = System.currentTimeMillis();
        if(zipFile == null){
            log.error("压缩包文件名为空!");
            return;
        }
        if(!zipFile.getName().endsWith(".zip")){
            log.error("压缩包文件名异常,zipFile={}", zipFile.getPath());
            return;
        }
        ZipOutputStream zos = null;
        FileOutputStream out = null;
        try {
            out=new FileOutputStream(zipFile);
            //需要指定GBK,否则中文备注乱码
            zos = new ZipOutputStream(out, Charset.forName("GBK"));
            for (File srcFile : srcFiles) {
                byte[] buf = new byte[BUFFER_SIZE];
                zos.putNextEntry(new ZipEntry(srcFile.getName()));
                int len;
                FileInputStream in = new FileInputStream(srcFile);
                while ((len = in.read(buf)) != -1) {
                    zos.write(buf, 0, len);
                }
                in.close();
            }

            zos.setComment("打包下载");
            long end = System.currentTimeMillis();
            log.info("压缩用时:" +(end - start)+ " ms");
        } catch (Exception e) {
            log.error("压缩出现异常, ", e);
            throw new RuntimeException("压缩时有异常发生,",e);
        }finally {
            try {
                zos.closeEntry();
                zos.close();
                out.close();
            }catch (Exception e){
                throw new RuntimeException("输出流关闭异常!", e);
            }

        }
    }


    public static void main(String args[]){
        ArrayList<File> files = new ArrayList<>();
        String  frontUrl="D:\\upload\\00a5036a-07d3-4131-b677-956312bbbc2c.jpg";
        String backUrl="D:\\upload\\1a200710-8c41-4411-8edf-a49575807a08.jpg";
        File frontImg = new File(frontUrl);
        File backImg = new File(backUrl);
        files.add(frontImg);
        files.add(backImg);
        File file = new File("E:\\testBack.zip");
        ZipUtil.toZip(files,file);

    }
}

效果截图:

 

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值