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);
}
}
}
}

}
posted @   闲人鹤  阅读(12999)  评论(7编辑  收藏  举报
编辑推荐:
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 没有源码,如何修改代码逻辑?
阅读排行:
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 记一次.NET内存居高不下排查解决与启示
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
· DeepSeek 开源周回顾「GitHub 热点速览」
点击右上角即可分享
微信分享提示