zoukankan      html  css  js  c++  java
  • Java打包多文件成zip

    package com.zh.java.util;

    import lombok.extern.slf4j.Slf4j;

    import java.io.File;
    import java.io.FileInputStream;
    import java.io.FileOutputStream;
    import java.io.IOException;
    import java.util.List;
    import java.util.zip.ZipEntry;
    import java.util.zip.ZipOutputStream;

    import static org.springframework.util.StreamUtils.BUFFER_SIZE;

    /**
    * Author: zh
    * Desc: 压缩包工具类
    * Date: Created in 2018/5/19 13:51
    */
    @Slf4j
    public class ZipUtil {

    /**
    * 把文件集合打成zip压缩包
    * @param srcFiles 压缩文件集合
    * @param zipFile zip文件名
    * @throws RuntimeException 异常
    */
    public static void toZip(List<File> srcFiles, File zipFile) throws RuntimeException {
    long start = System.currentTimeMillis();
    if(zipFile == null){
    log.error("压缩包文件名为空!");
    return;
    }
    if(!zipFile.getName().endsWith(".zip")){
    log.error("压缩包文件名异常,zipFile={}", zipFile.getPath());
    return;
    }
    ZipOutputStream zos = null;
    try {
    FileOutputStream out = new FileOutputStream(zipFile);
    zos = new ZipOutputStream(out);
    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);
    }
    zos.setComment("我是注释");
    zos.closeEntry();
    in.close();
    out.close();
    }
    long end = System.currentTimeMillis();
    log.info("压缩完成,耗时:" + (end - start) + " ms");
    } catch (Exception e) {
    log.error("ZipUtil toZip exception, ", e);
    throw new RuntimeException("zipFile error from ZipUtils", e);
    } finally {
    if (zos != null) {
    try {
    zos.close();
    } catch (IOException e) {
    log.error("ZipUtil toZip close exception, ", e);
    }
    }
    }
    }

    }
  • 相关阅读:
    Docker 我的常用命令
    Docker 已运行容器修改配置
    Docker .NET Core项目run起来
    Docker 安装运行mssql-server-linux
    Docker Mssql 还原数据库到Linux
    Nginx(四)------nginx 负载均衡
    nginx(二)------nginx.conf 配置文件
    Nginx(一)------简介与安装
    MySQL主从复制作用和原理
    设计模式:策略模式
  • 原文地址:https://www.cnblogs.com/huanshilang/p/10601712.html
Copyright © 2011-2022 走看看