package zip;
import org.apache.tools.zip.ZipEntry;
import org.apache.tools.zip.ZipFile;
import java.io.*;
import java.util.Enumeration;
public class UnzipUntil {
public static void main(String[] args) throws IOException {
/**
* 解壓檔案
*/
File zipFile = new File("C:\\Users\\Administrator\\Desktop\\test\\2222");
is_or_not_a_Dic(zipFile);
}
private static void is_or_not_a_Dic(File zipFile) {
String aimpath = null;
if (zipFile.isDirectory()) {
File[] listFiles = zipFile.listFiles();
for (int i = 0; i < listFiles.length; i++) {
//循環周遊 :如果listFiles[i]是目錄,則判斷目錄中是否有壓縮包,若有,則解壓到相應的位置
if (listFiles[i].isDirectory()) {
is_or_not_a_Dic(listFiles[i]);
}
//如果listFiles[i]是檔案,确實自拍壓縮包,則解壓
if (listFiles[i].toString().endsWith(".zip")) {
try {
aimpath = listFiles[i].getAbsolutePath().replaceAll(".zip", ""); //解壓檔案的父目錄
unZipFiles(listFiles[i], aimpath);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} //listFiles[i]:需要解壓的壓縮包 aimpath:解壓的的目錄(同級目錄)
}
}
} else {
if (zipFile.toString().endsWith(".zip")) {
aimpath = zipFile.getAbsolutePath().replaceAll(".zip", ""); //解壓檔案的父目錄
try {
unZipFiles(zipFile, aimpath); //listFiles[i]:需要解壓的壓縮包 aimpath:解壓的的目錄(同級目錄)
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
/**
* 解壓到指定目錄
*
* @param zipPath
* @param descDir
*/
public static void unZipFiles(String zipPath, String descDir) throws IOException {
unZipFiles(new File(zipPath), descDir);
}
/**
* 解壓檔案到指定目錄
*
* @param zipFile
* @param descDir
*/
@SuppressWarnings("rawtypes")
public static void unZipFiles(File zipFile, String descDir) throws IOException {
//建立目錄檔案
File pathFile = new File(descDir);
if (!pathFile.exists()) {
pathFile.mkdirs();
}
@SuppressWarnings("resource")
ZipFile zip = new ZipFile(zipFile);
for (Enumeration entries = zip.getEntries(); entries.hasMoreElements(); ) {
ZipEntry entry = (ZipEntry) entries.nextElement();
String zipEntryName = entry.getName();
InputStream in = zip.getInputStream(entry);
String outPath = (descDir + "/" + zipEntryName).replaceAll("\\*", "/");
//判斷路徑是否存在,不存在則建立檔案路徑
File file = new File(outPath.substring(0, outPath.lastIndexOf('/')));
if (!file.exists()) {
file.mkdirs();
}
//判斷檔案全路徑是否為檔案夾,如果是上面已經上傳,不需要解壓
if (new File(outPath).isDirectory()) {
continue;
}
//輸出檔案路徑資訊
System.out.println(outPath);
OutputStream out = new FileOutputStream(outPath);
byte[] buf1 = new byte[1024];
int len;
while ((len = in.read(buf1)) > 0) {
out.write(buf1, 0, len);
}
in.close();
out.close();
}
System.out.println("******************解壓完畢********************");
}
}
pom依賴
<dependency>
<groupId>org.apache.ant</groupId>
<artifactId>ant</artifactId>
<version>1.10.8</version>
</dependency>
<dependency>
<groupId>net.sourceforge.jexcelapi</groupId>
<artifactId>jxl</artifactId>
<version>2.6.12</version>
</dependency>