/*
提供zip檔案的解壓縮介面:
AdapterZipFile:
輸入:zipFileName(zip檔案的絕對路徑),outputDirectory(zip檔案解壓縮後的存放路徑)
輸出:
說明:初始化函數
unZipFile:
輸入:無
輸出:
說明:解壓縮zip檔案,解壓縮後存放到outputDirectory路徑下
GetZipFileList:
輸入:無
輸出:list
說明:解壓縮後的檔案清單絕對路徑存放在ArrayList動態數組中
*/
package com.mop.pushmail.adapter.htmlziprar;
import java.io.*;
import java.util.*;
import org.apache.tools.zip.*;
public class AdapterZipFile {
String zipFileName = null;//zip檔案的絕對路徑
String outputDirectory = null;//zip檔案解壓縮後的存放路徑
ArrayList list = new ArrayList();//檔案解壓縮後的檔案清單絕對路徑
// public AdapterZipFile(String zipFileName) {
// if(zipFileName == null){
// return;
// }
// this.zipFileName = zipFileName.replace("/","//");
// unZipFile();
// }
//初始化
public AdapterZipFile(String zipFileName, String outputDirectory){
if(zipFileName == null){
return;
}
this.zipFileName = zipFileName;
if(outputDirectory != null){
this.outputDirectory = outputDirectory;
}else{
this.outputDirectory = zipFileName.substring(0,
zipFileName.replace('//', '/').lastIndexOf("/"));
}
// unZipFile();
}
//建立目錄
private void createDirectory(String directory, String subDirectory) {
String dir[];
File fl = new File(directory);
try {
if (subDirectory == "" && fl.exists() != true)
fl.mkdirs();
else if (subDirectory != "") {
dir = subDirectory.replace("//","/").split("/");
for (int i = 0; i < dir.length; i++) {
File subFile = new File(directory + File.separator + dir[i]);
if (!subFile.exists())
subFile.mkdir();
directory += File.separator + dir[i];
}
}
}catch (Exception ex) {
System.out.println(ex.getMessage());
}
}
//解壓縮檔案
//如果outputDierctory為null,解壓到zipFileName檔案的目前的目錄下
public void unZipFile() {
File file = new File(zipFileName);
if (!file.exists()) {
return;
}
createDirectory(outputDirectory, "");
try {
ZipFile zipFile = new ZipFile(zipFileName);
Enumeration e = zipFile.getEntries();
ZipEntry zipEntry = null;
while (e.hasMoreElements()) {
zipEntry = (ZipEntry) e.nextElement();
if (zipEntry.isDirectory()) {
String name = zipEntry.getName();
name = name.substring(0, name.length() - 1);
File f = new File(outputDirectory + File.separator + name);
f.mkdir();
} else {
String fileName = zipEntry.getName();
fileName = fileName.replace('//', '/');
//檔案在多層目錄下 這時需要建立目錄如:d1/d2/1.txt
if (fileName.indexOf("/") != -1) {
createDirectory(outputDirectory, fileName.substring(0,
fileName.lastIndexOf("/")));
fileName = fileName.substring(
fileName.lastIndexOf("/") + 1, fileName
.length());
}
list.add(outputDirectory + File.separator
+ zipEntry.getName());
File f = new File(outputDirectory + File.separator
+ zipEntry.getName());
f.createNewFile();
InputStream in = zipFile.getInputStream(zipEntry);
FileOutputStream out = new FileOutputStream(f);
byte[] by = new byte[1024];
int c;
while ((c = in.read(by)) != -1) {
out.write(by, 0, c);
}
out.close();
in.close();
}
}
} catch (Exception ex) {
System.out.println(ex.getMessage());
}
}
//返回zip檔案解壓撒後檔案清單的絕對路徑
public ArrayList GetZipFileList(){
return list;
}
}