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

}

}

}

}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值