版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_32403351/article/details/80623024
前几天在网上看到过这种,但是觉得还是不怎么通用,
就自己了解原理尝试的写了个工具类,希望大家多多指点,不说多了上代码了:
package com.bdt.framework.zip; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.*; import java.util.Enumeration; import java.util.zip.ZipEntry; import java.util.zip.ZipFile; /** * zip 工具类 * @author zhanghongbo */ public class ZipUilt { private static final Logger log = LoggerFactory.getLogger(ZipUilt.class); /** * 解压缩zip包 * * @param zipFilePath zip文件的全路径 * @param unzipFilePath 解压后的文件保存的路径 */ @SuppressWarnings("unchecked") public static void unzip(String zipFilePath, String unzipFilePath) throws Exception { log.info("Unzipped files:{}", zipFilePath); //解压后的文件路径是否存在,不存在则新建 File unzip=new File(unzipFilePath); if(!unzip.isDirectory()){ log.info("create unzip files path:{}",unzipFilePath); unzip.mkdirs(); } //开始解压 String entryDirPath; ZipFile zip = null; InputStream is = null; OutputStream os = null; try { File zipFile = new File(zipFilePath); zip = new ZipFile(zipFile); Enumeration entries = zip.entries(); //循环对压缩包里的每一个文件进行解压 while (entries.hasMoreElements()) { ZipEntry entry = (ZipEntry) entries.nextElement(); //构建压缩包中一个文件解压后保存的文件全路径 String entryFilePath = unzipFilePath + "/" + entry.getName(); //构建解压后保存的文件夹路径 int index = entryFilePath.lastIndexOf("/"); if (index != -1) { entryDirPath = entryFilePath.substring(0, index); } else { entryDirPath = ""; } File entryDir = new File(entryDirPath); //如果文件夹路径不存在,则创建文件夹 if (!entryDir.exists() || !entryDir.isDirectory()) { log.info("Create folder path:{}", entryDirPath); entryDir.mkdirs(); continue; } //写入文件 byte[] buffer = new byte[4*1024]; int len; os = new BufferedOutputStream(new FileOutputStream(new File(entryFilePath))); is = new BufferedInputStream(zip.getInputStream(entry)); while ((len = is.read(buffer, 0, 4*1024)) != -1) { os.write(buffer, 0, len); } is.close(); log.info("===========Unzipped file ove===========:{}",entryFilePath); } } catch (Exception e) { log.error("Unzipped file failed, error message:{}", e); } finally { try { if (zip != null) { zip.close(); } else if (os != null) { os.close(); } else if (is != null) { is.close(); } } catch (Exception e) { log.error("close error:{}", e); e.printStackTrace(); } } } public static void main(String[] args) throws Exception { String zipFilePath = "D:/0382cd69cd9dd647ace82c6a/0382cd69cd9dd647ace82c6a.zip"; String unzipFilePath = "D:/test"; try { unzip(zipFilePath, unzipFilePath); } catch (Exception e) { e.printStackTrace(); } } }
到这里就结束了,有问题还请大家给小编提出来,谢谢!