概述:项目中有个多文件打包下载的需求,需要实现一个多文件打包的工具类,工具类基于jdk1.8的API。
我的需求:如下图
工具类实现:
import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.nio.charset.Charset; import java.util.ArrayList; import java.util.List; import java.util.zip.ZipEntry; import java.util.zip.ZipOutputStream; import static org.springframework.util.StreamUtils.BUFFER_SIZE; /** * Author: liujian */ public class ZipUtil { private static final Logger log = LoggerFactory.getLogger(ZipUtil.class); public static void toZip(List<File> srcFiles, File zipFile) { long start = System.currentTimeMillis(); if(zipFile == null){ log.error("压缩包文件名为空!"); return; } if(!zipFile.getName().endsWith(".zip")){ log.error("压缩包文件名异常,zipFile={}", zipFile.getPath()); return; } ZipOutputStream zos = null; FileOutputStream out = null; try { out=new FileOutputStream(zipFile); //需要指定GBK,否则中文备注乱码 zos = new ZipOutputStream(out, Charset.forName("GBK")); 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); } in.close(); } zos.setComment("打包下载"); long end = System.currentTimeMillis(); log.info("压缩用时:" +(end - start)+ " ms"); } catch (Exception e) { log.error("压缩出现异常, ", e); throw new RuntimeException("压缩时有异常发生,",e); }finally { try { zos.closeEntry(); zos.close(); out.close(); }catch (Exception e){ throw new RuntimeException("输出流关闭异常!", e); } } } public static void main(String args[]){ ArrayList<File> files = new ArrayList<>(); String frontUrl="D:\\upload\\00a5036a-07d3-4131-b677-956312bbbc2c.jpg"; String backUrl="D:\\upload\\1a200710-8c41-4411-8edf-a49575807a08.jpg"; File frontImg = new File(frontUrl); File backImg = new File(backUrl); files.add(frontImg); files.add(backImg); File file = new File("E:\\testBack.zip"); ZipUtil.toZip(files,file); } }
效果截图: