2016-08-24 88 views
4

我有一個接受包含XML文件的ZIP文件的servlet。我想閱讀這些XML文件的內容,但我得到一個java.io.IOException:流關閉。閱讀ZipEntry中的字符串:java.io.IOException:Stream已關閉

我得到的ZIP像這樣:

private byte[] getZipFromRequest(HttpServletRequest request) throws IOException { 
    byte[] body = new byte[request.getContentLength()]; 
    new DataInputStream(request.getInputStream()).readFully(body); 
    return body; 
} 

我看它像這樣:

public static void readZip(byte[] zip) throws IOException { 

    ByteArrayInputStream in = new ByteArrayInputStream(zip); 
    ZipInputStream zis = new ZipInputStream(in); 

    ZipEntry entry; 

    while ((entry = zis.getNextEntry()) != null) { 
     System.out.println(String.format("Entry: %s len %d", entry.getName(), entry.getSize())); 

     BufferedReader br = new BufferedReader(new InputStreamReader(zis, "UTF-8")); 
     String line; 
     while ((line = br.readLine()) != null) { 
      System.out.println(line); 
     } 
     br.close(); 
    } 
    zis.close(); 
} 

輸出:

Entry: file.xml len 3459 
<?xml version="1.0" encoding="UTF-8" standalone="yes"?> 
<test> 
correct content of my xml file 
</test> 
java.io.IOException: Stream closed 
    at java.util.zip.ZipInputStream.ensureOpen(ZipInputStream.java:67) 
    at java.util.zip.ZipInputStream.getNextEntry(ZipInputStream.java:116) 
    at util.ZipHelper.readZip(ZipHelper.java:26) 

我的問題

爲什麼我在這條線上得到這個豁免?

while ((entry = zis.getNextEntry()) != null) { 

我錯過了什麼?

回答

3

您正在打包您的zisBufferedReader因此當您關閉br時,zis也將關閉。

因此刪除br.close迭代將繼續進行,沒有任何異常。

+0

就是這樣。我應該將該聲明從循環中取出並關閉它嗎?有沒有更好的方法來做到這一點? – Tim