作者:曾巧(numenzq)
最近做的一個項目需要用Java程序讀寫Zip文件,迫于找不到好的工具類來處理,也只好用java.util.zip包提供的類來實現Zip文件的壓縮和解壓操作了,在這之前你需要了解以下幾個基本概念:
- ZipEntry:This class is used to represent a ZIP file entry.
- ZipFile:This class is used to read entries from a zip file.
- ZipInputStream:This class implements an input stream filter for reading files in the ZIP file format.
- ZipOutputStream:This class implements an output stream filter for writing files in the ZIP file format.
現在我們了解一下讀寫Zip文件的基本流程。當解壓時,從該Zip文件輸入流中讀取出ZipEntry,然后根據ZipEntry的信息,讀取對應文件的相應字節。代碼實現如下:
publicsynchronizedstatic Map<String, byte[]> unZip(InputStream is)
throws IOException {
Map<String, byte[]> result = new HashMap<String, byte[]>();
byte[] buf;
ZipInputStream zis = new ZipInputStream(is);
ZipEntry zipEntry = zis.getNextEntry();
while (zipEntry != null) {
if (zipEntry.isDirectory()) {
zipEntry = zis.getNextEntry();
continue;
} else {
buf = newbyte[(int) zipEntry.getSize()];
zis.read(buf, 0, (int) zipEntry.getSize());
result.put(zipEntry.getName(), buf);
zipEntry = zis.getNextEntry();
}
}
return result;
}
壓縮操作與解壓操作差不多,先將文件字節流組裝成ZipEntry,然后把ZipEntry加入到輸出流中即可。代碼實現如下:
publicsynchronizedstaticByteArrayOutputStream zip(Map<String, byte[]> map)
throws IOException {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ZipOutputStream zos = new ZipOutputStream(baos);
ZipEntry zipEntry;
for (String key : map.keySet()) {
zipEntry = new ZipEntry(key);
zipEntry.setSize(map.get(key).length);
zipEntry.setTime(System.currentTimeMillis());
zos.putNextEntry(zipEntry);
zos.write(map.get(key));
zos.flush();
}
zos.close();
return baos;
}
至此,使用上面的兩個方法就能完成基本的Zip文件壓縮和解壓縮處理了;該方法只適合處理Zip格式的文件,對于GZip格式的文件,我相信你也能輕松搞定了:)。
posted on 2009-12-09 09:50
super_nini 閱讀(865)
評論(0) 編輯 收藏