欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

Java打包多文件成zip

程序员文章站 2022-04-08 19:08:42
package com.zh.java.util;import lombok.extern.slf4j.Slf4j;import java.io.File;import java.io.FileInputStream;import java.io.FileOutputStream;import ja ......
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);
}
}
}
}

}