Java 1.1 提供完整的 Zip 支援,可壓縮多個檔案並計算校驗和。標準 Zip 格式確保與現有工具相容。
// 壓縮
FileOutputStream f = new FileOutputStream("test.zip");
CheckedOutputStream csum = new CheckedOutputStream(f, new Adler32());
ZipOutputStream out = new ZipOutputStream(new BufferedOutputStream(csum));
out.setComment("註解");
for (String file : args) {
out.putNextEntry(new ZipEntry(file));
// 讀取檔案內容寫入 out
in.close();
}
out.close(); // 必須關閉才能取得正確校驗和
// 解壓縮
ZipInputStream in2 = new ZipInputStream(new BufferedInputStream(
new CheckedInputStream(new FileInputStream("test.zip"), new Adler32())));
ZipEntry ze;
while ((ze = in2.getNextEntry()) != null) {
// 讀取 ze 內容
}
// 替代方案:ZipFile 列舉條目
ZipFile zf = new ZipFile("test.zip");
Enumeration e = zf.entries();
Adler32(較快)與 CRC32(較準確),但 ZipEntry 僅支援 CRC 介面ZipInputStream 無法讀取,僅能透過 ZipEntry 逐條目存取不限於檔案,任何資料流(含網路連線)皆可壓縮傳輸。