1 回答

TA貢獻(xiàn)1829條經(jīng)驗(yàn) 獲得超4個(gè)贊
ZipInputStream
每次迭代入口指針時(shí),都會(huì)丟失入口指針,因?yàn)槊總€(gè) ZipInputStream 對(duì)象只允許一個(gè)流。
try (ZipInputStream is = new ZipInputStream(Zippy.class.getResourceAsStream("file.zip"))) {
ZipEntry entry;
while ((entry = is.getNextEntry()) != null) {
if (!entry.isDirectory()) {
// do your logic here (get the entry name)
}
is.closeEntry();
}
}
來自javadocs:
closeEntry() -Closes the current ZIP entry and positions the stream for reading the next entry.
getNextEntry() - Reads the next ZIP file entry and positions the stream at the beginning of the entry data.
基本上,您在任何給定時(shí)間只能打開一個(gè)條目。
因此,如果你想做你正在做的事情,你能做的最好的就是保存 zip 條目的名稱并遍歷 ZipInputStream 以將指針移動(dòng)到正確的位置,然后你可以使用 ZipInputStream.read() 來獲取字節(jié)。
壓縮文件
如果您可以使用 ZipFile 對(duì)象(而不是 ZipInputStream),您就可以做您想要完成的事情。
static void loadMap() throws IOException {
ZipFile file = new ZipFile("testzip.zip");
Enumeration<? extends ZipEntry> entries = file.entries();
while (entries.hasMoreElements()) {
ZipEntry entry = entries.nextElement();
if (!entry.isDirectory()) {
streamMap.put(entry.getName(), new BufferedReader(new InputStreamReader(file.getInputStream(entry))));
}
}
}
public static void main(String[] args) throws IOException {
loadMap();
Iterator<BufferedReader> iter = streamMap.values().iterator();
while (iter.hasNext()) {
BufferedReader reader = iter.next();
String line;
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
}
}
OUTPUT:
file 2: First line!
file 2: Second Line!
file 1: First line!
file 1 : Second Line!
BUILD SUCCESSFUL (total time: 0 seconds)
您只需要記住保存 zip 文件引用并file.close();在完成后調(diào)用。
添加回答
舉報(bào)