[英]extracting contents of ZipFile entries when read from byte[] (Java)
我有一個zip文件,其內容顯示為byte [] 但原始文件對象不可訪問 。 我想閱讀每個條目的內容。 我能夠從字節的ByteArrayInputStream創建一個ZipInputStream,並可以讀取條目及其名稱。 但是,我看不到一種簡單的方法來提取每個條目的內容。
(我看過Apache Commons,但也看不到那么簡單的方法)。
UPDATE @ Rich的代碼似乎解決了這個問題,謝謝
QUERY為什么兩個例子的乘數都是* 4(128/512和1024 * 4)?
如果要處理流中的嵌套zip條目,請參閱此答案以獲取提示。 因為內部條目是按順序列出的,所以可以通過獲取每個條目的大小並從流中讀取那么多字節來處理它們。
更新了將每個條目復制到標准輸出的示例:
ZipInputStream is;//obtained earlier
ZipEntry entry = is.getNextEntry();
while(entry != null) {
copyStream(is, out, entry);
entry = is.getNextEntry();
}
...
private static void copyStream(InputStream in, OutputStream out,
ZipEntry entry) throws IOException {
byte[] buffer = new byte[1024 * 4];
long count = 0;
int n = 0;
long size = entry.getSize();
while (-1 != (n = in.read(buffer)) && count < size) {
out.write(buffer, 0, n);
count += n;
}
}
它實際上使用ZipInputStream
作為InputStream
(但不要在每個條目的末尾關閉它)。
計算下一個ZipEntry的開頭有點棘手。 請參閱JDK 6中包含的此示例,
public static void main(String[] args) {
try {
ZipInputStream is = new ZipInputStream(System.in);
ZipEntry ze;
byte[] buf = new byte[128];
int len;
while ((ze = is.getNextEntry()) != null) {
System.out.println("----------- " + ze);
// Determine the number of bytes to skip and skip them.
int skip = (int)ze.getSize() - 128;
while (skip > 0) {
skip -= is.skip(Math.min(skip, 512));
}
// Read the remaining bytes and if it's printable, print them.
out: while ((len = is.read(buf)) >= 0) {
for (int i=0; i<len; i++) {
if ((buf[i]&0xFF) >= 0x80) {
System.out.println("**** UNPRINTABLE ****");
// This isn't really necessary since getNextEntry()
// automatically calls it.
is.closeEntry();
// Get the next zip entry.
break out;
}
}
System.out.write(buf, 0, len);
}
}
is.close();
} catch (Exception e) {
e.printStackTrace();
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.