java压缩工具类
package com.sgcc.admin.common.utils; import org.apache.commons.io.IOUtils; import org.slf4j.LoggerFactory; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.util.zip.ZipEntry; import java.util.zip.ZipOutputStream; /** * @Description: 文件压缩处理类 * @author * @version v1.0 * @CreateDate 2019年1月10日 */ public class ZipUtils { private static org.slf4j.Logger logger = LoggerFactory.getLogger(ZipUtils.class); private ZipUtils(){ } public static void doCompress(String srcFile, String zipFile) throws IOException { doCompress(new File(srcFile), new File(zipFile)); } /** * 文件压缩 * @param srcFile 目录或者单个文件 * @param zipFile 压缩后的ZIP文件 */ public static void doCompress(File srcFile, File zipFile) throws IOException { //待压缩文件路径不存在 if(!srcFile.exists()){ logger.info("文件下载路径不存在!"); return; } //压缩文件路径不存在,需要创建目录 File dir = zipFile.getParentFile(); if(!dir.exists()){ dir.mkdirs(); } ZipOutputStream out = null; try { out = new ZipOutputStream(new FileOutputStream(zipFile)); doCompress(srcFile, out); }finally { IOUtils.closeQuietly(out);//记得关闭资源 } } public static void doCompress(File file, ZipOutputStream out) throws IOException{ doCompress(file, out, ""); } public static void doCompress(File inFile, ZipOutputStream out, String dir) throws IOException { if ( inFile.isDirectory() ) { File[] files = inFile.listFiles(); if (files!=null && files.length>0) { for (File file : files) { String name = inFile.getName(); if (!"".equals(dir)) { name = dir + File.separator + name; } ZipUtils.doCompress(file, out, name);//递归 } } } else { ZipUtils.doZip(inFile, out, dir); } } /** * @Description: 压缩方法 * @param inFile 待压缩文件,out 压缩流,dir 压缩文件路径 * @return * @author * @date 2019年1月10日 */ public static void doZip(File inFile, ZipOutputStream out, String dir) throws IOException { FileInputStream fis = null; try { String entryName = null; if (!"".equals(dir)) { entryName = dir + File.separator + inFile.getName(); } else { entryName = inFile.getName(); } ZipEntry entry = new ZipEntry(entryName); out.putNextEntry(entry); int len = 0 ; byte[] buffer = new byte[1024]; fis = new FileInputStream(inFile); while ((len = fis.read(buffer)) > 0) { out.write(buffer, 0, len); out.flush(); } }finally { IOUtils.closeQuietly(fis);//记得关闭资源 } } public static void main(String[] args) throws IOException { doCompress("D:/logs", "D:/log11/log.zip"); } }