java zip 解压缩 maven工程 引入坐标
<!-- ZIP文件解压缩 --> <dependency> <groupId>net.lingala.zip4j</groupId> <artifactId>zip4j</artifactId> <version>1.3.2</version> </dependency>
zip 解压缩工具类
代码如下
1 package com.guohua.yunwei.util; 2 3 import java.io.File; 4 5 import net.lingala.zip4j.core.ZipFile; 6 import net.lingala.zip4j.model.ZipParameters; 7 import net.lingala.zip4j.util.Zip4jConstants; 8 9 public class ZIPUtil { 10 /** 11 * todo zip解压缩 12 * @param source 压缩文件全路径 13 * @param target 要解压路径 14 * @param targetName 解压文件夹名称 15 */ 16 public static void unzip (String source,String target,String targetName) throws Exception{ 17 try { 18 File file = new File(source); 19 if(!file.exists() || file.isDirectory()){ 20 throw new Exception("将要解压文件不存在或路径填写不正确!"); 21 } 22 23 file = new File(target+File.separator+targetName); 24 if(!file.exists()){ 25 file.mkdirs(); 26 System.out.println("路劲不存在,创建路径"); 27 } 28 ZipFile zipfile = new ZipFile(source); 29 if (!zipfile.isValidZipFile()) { 30 throw new Exception("压缩文件不合法,可能被损坏."); 31 } 32 zipfile.setFileNameCharset("GBK"); 33 zipfile.extractAll(target+File.separator+targetName); 34 } catch (Exception e) { 35 e.printStackTrace(); 36 throw e; 37 } 38 39 40 } 41 42 /** 43 * todo 生成zip压缩 44 * @param source 要压缩文件全路径 45 * @param target 压缩文件存放路径 46 * @param targetName 解压文件名称 47 */ 48 public static void zip (String source,String target,String targetName) throws Exception{ 49 try { 50 File file = new File(target); 51 if(!file.exists()){ 52 file.mkdirs(); 53 System.out.println("解压存储路劲不存在,创建路径"); 54 } 55 file = new File(source); 56 if(!file.exists()){ 57 throw new Exception("将要解压文件不存在或路径填写不正确!"); 58 } 59 60 ZipFile zipfile = new ZipFile(target+File.separator+targetName); 61 zipfile.setFileNameCharset("GBK"); 62 ZipParameters params = new ZipParameters(); 63 params.setCompressionMethod(Zip4jConstants.COMP_DEFLATE); // 压缩方式 64 params.setCompressionLevel(Zip4jConstants.DEFLATE_LEVEL_NORMAL); // 压缩级别 65 66 if(file.isFile()){ 67 zipfile.addFile(file, params); 68 }else{ 69 zipfile.addFolder(source, params); 70 } 71 72 } catch (Exception e) { 73 e.printStackTrace(); 74 throw e; 75 } 76 77 78 } 79 80 public static void main(String[] args) { 81 try { 82 //unzip("D:/log/157wls.log.20210412.bz2","D:\\","157wls.log.20210412"); 83 zip("C:\\Users\\yuanfeng_lhyd\\Desktop\\ANT蚂蚁退保数据\\endorse_1.csv","C:\\Users\\yuanfeng_lhyd\\Desktop\\ANT蚂蚁退保数据","endorse_1.zip"); 84 } catch (Exception e) { 85 // TODO Auto-generated catch block 86 e.printStackTrace(); 87 } 88 } 89 90 }