類ZipInputStream讀出ZIP文件序列(簡單地說就是讀出這個ZIP文件壓縮了多少文件),而類ZipFile使用內嵌的隨機文件訪問機制讀出其中的文件內容,因此沒必要順序的讀出ZIP壓縮文件序列。
ZipInputStream和ZipFile之間另一個基本的不一樣點在於高速緩衝的使用方面。當文件使用ZipInputStream和FileInputStream流讀出的時候,ZIP條目不使用高速緩衝。然而,若是使用ZipFile(文件名)來打開文件,它將使用內嵌的高速緩衝,因此若是ZipFile(文件名)被重複調用的話,文件只被打開一次。緩衝值在第二次打開時使用。若是你工做在UNIX系統下,這是什麼做用都沒有的,由於使用ZipFile打開的全部ZIP文件都在內存中存在映射,因此使用ZipFile的性能優於ZipInputStream。然而,若是同一ZIP文件的內容在程序執行期間常常改變,或是重載的話,使用ZipInputStream就成爲你的首選了。
下面顯示了使用類ZipFile來解壓一個ZIP文件的過程:性能
經過指定一個被讀取的ZIP文件,或者是文件名,或者是一個文件對象來建立一個ZipFile對象:spa
Java代碼 對象
ZipFile zipfile = new ZipFile("figs.zip"); ip
使用entries方法,返回一個枚舉對象,循環得到文件的ZIP條目對象:內存
Java代碼 get
while(e.hasMoreElements()) { it
entry = (ZipEntry) e.nextElement(); io
// read contents and save them class
} test
ZIP條目做爲參數傳遞給getInputStream方法,能夠讀取ZIP文件中指定條目的內容,能過其返回的輸入流(InputStram)對象能夠方便的讀出ZIP條目的內容:
Java代碼
is = new BufferedInputStream(zipfile.getInputStream(entry));
獲取ZIP條目的文件名,建立輸出流,並保存:
Java代碼
byte data[] = new byte[BUFFER];
FileOutputStream fos = new FileOutputStream(entry.getName());
dest = new BufferedOutputStream(fos, BUFFER);
while ((count = is.read(data, 0, BUFFER)) != -1) {
dest.write(data, 0, count);
}
最後關閉全部的輸入輸出流
Java代碼
dest.flush();
dest.close();
is.close();
完整代碼:
Java代碼
public class UnZip2 {
static final int BUFFER = 2048;
public static void main(String argv[]) {
String fileName = "c:/testlog.zip";
String unZipDir = "c:/2/2/";
unZip(fileName, unZipDir);
}
public static void unZip(String fileName, String unZipDir) {
try {
// 先判斷目標文件夾是否存在,若是不存在則新建,若是父目錄不存在也新建
File f = new File(unZipDir);
if (!f.exists()) {
f.mkdirs();
}
BufferedOutputStream dest = null;
BufferedInputStream is = null;
ZipEntry entry;
ZipFile zipfile = new ZipFile(fileName);
Enumeration e = zipfile.entries();
while (e.hasMoreElements()) {
entry = (ZipEntry) e.nextElement();
System.out.println("Extracting: " + entry);
is = new BufferedInputStream(zipfile.getInputStream(entry));
int count;
byte data[] = new byte[BUFFER];
FileOutputStream fos = new FileOutputStream(unZipDir + "/"
+ entry.getName());
System.out.println("entry.getName(): " + entry.getName());
dest = new BufferedOutputStream(fos, BUFFER);
while ((count = is.read(data, 0, BUFFER)) != -1) {
dest.write(data, 0, count);
}
dest.flush();
dest.close();
is.close();
}
} catch (Exception e) {
e.printStackTrace();
}
}
public static boolean makeDir(String unZipDir) {
boolean b = false;
try {
File f = new File(unZipDir);
if (!f.exists()) {
b = f.mkdirs();
}
} catch (Exception e) {
e.printStackTrace();
return b;
}
return b;
}
}