import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
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;
/**
* Desc: 压缩包工具类
*/
public class ZipUtil {
private final static Logger logger = LoggerFactory.getLogger(ZipUtil.class);
public static void toZip(List<File> srcFiles, File zipFile) throws RuntimeException {
long start = System.currentTimeMillis();
if(zipFile == null){
logger.error("压缩包文件名为空!");
return;
}
if(!zipFile.getName().endsWith(".zip")){
logger.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.closeEntry();
in.close();
}
long end = System.currentTimeMillis();
logger.info("压缩完成,耗时:" + (end - start) + " ms");
} catch (Exception e) {
logger.error("ZipUtil toZip exception, ", e);
throw new RuntimeException("zipFile error from ZipUtils", e);
} finally {
if (zos != null) {
try {
zos.close();
} catch (IOException e) {
logger.error("ZipUtil toZip close exception, ", e);
}
}
}
}
}
压缩包工具类
猜你喜欢
转载自blog.csdn.net/huanshilang1985/article/details/82903726
今日推荐
周排行