代码:

1 package com.xiaobai; 2 3 import java.io.File; 4 import java.io.FileOutputStream; 5 import java.io.IOException; 6 import java.io.InputStream; 7 import java.nio.charset.Charset; 8 import java.util.Enumeration; 9 import java.util.zip.ZipEntry; 10 import java.util.zip.ZipFile; 11 12 public class UnZipUtils { 13 14 public static void main(String[] args) { 15 try { 16 //将temp下所有的压缩文件解压 17 unzipFromLoc("F:\BaiduNetdiskDownload\03_Hadoop"); 18 } catch (Exception e) { 19 e.printStackTrace(); 20 } 21 } 22 23 //从总目录下解压文件里所有的压缩包至目的文件路径 24 public static void unzipFromLoc(String filePath) throws Exception{ 25 File file = new File(filePath); 26 File[] list = file.listFiles();//固定元素,不包含新产生的 27 String from = ""; 28 for(File f : list){ 29 if(f.isDirectory()) { 30 unzipFromLoc(f.getAbsolutePath()); 31 }else { 32 boolean bool = f.isFile(); 33 if(bool){ 34 from = f.getAbsolutePath(); 35 unZipFiles(new File(from),filePath); 36 } 37 } 38 } 39 } 40 41 /** 42 * 解压文件到指定目录 43 * 解压后的文件名,和之前一致 44 * @param zipFile 待解压的zip文件 45 * @param descDir 指定目录 46 */ 47 public static void unZipFiles(File zipFile, String descDir) throws IOException { 48 try{ 49 ZipFile zip = new ZipFile(zipFile, Charset.forName("GBK"));//解决中文文件夹乱码 50 File pathFile = new File(descDir); 51 if (!pathFile.exists()) { 52 pathFile.mkdirs(); 53 } 54 //即使有内层目录,目录里的文件也是可以在这里遍历出来的,只不过在内层目录之后,而且是带内层目录的全路径,所以解压时需要判断路径是否存在, 55 // 不存在则创建内层目录dir;判断一下内层目录,continue,目录里面的文件再写 56 for (Enumeration<? extends ZipEntry> entries = zip.entries(); entries.hasMoreElements();) { 57 ZipEntry entry = (ZipEntry) entries.nextElement(); 58 String zipEntryName = entry.getName(); 59 InputStream in = zip.getInputStream(entry); 60 String outPath = (descDir + File.separator + zipEntryName).replaceAll("\\", "/"); 61 File file = new File(outPath); 62 if(entry.isDirectory()) {//有内层文件夹,需要创建新的内层目录后continue,后面内层文件夹里的压缩文件才有合法新路径,否则内层文件夹里的压缩文件使用路径创建流时报拒绝访问异常,因为父目录不存在 63 file.mkdirs();//是文件而不是文件夹路径的不能写这个,会创建到以文件名为最终目录名的全目录导致与文件路径冲突,下面流关联文件时因读取了同名文件夹而发生异常 64 continue; 65 } 66 // 输出文件路径信息 67 System.out.println(outPath); 68 FileOutputStream out = new FileOutputStream(outPath); 69 byte[] buf1 = new byte[1024]; 70 int len; 71 while ((len = in.read(buf1)) > 0) { 72 out.write(buf1, 0, len); 73 } 74 in.close(); 75 out.close(); 76 // unZipFiles(file, outPath.substring(0, outPath.lastIndexOf('/')));//可递归解压zip,jar文件,不能解压rar文件 77 } 78 System.out.println("******************解压完毕********************"); 79 return; 80 }catch (Exception e) { 81 e.printStackTrace(); 82 } 83 } 84 }
参考:
https://blog.csdn.net/weixin_41722928/article/details/80832481
https://blog.csdn.net/SicongFu/article/details/84997715
https://blog.csdn.net/zcc_0015/article/details/40454777
java中正则匹配反斜杠问题: