2011-11-10 28 views
3

我創建一個程序,將提取一個zip,然後將文件插入到數據庫中,每隔一段時間,我得到了錯誤java的提取物拉鍊ZLIB輸入流意外結束

java.lang.Exception: java.io.EOFException: Unexpected end of ZLIB input stream 

我無法查明原因在於提取代碼與您可以在網上找到的所有其他代碼幾乎相同。我的代碼如下:

public void extract(String zipName, InputStream content) throws Exception { 

    int BUFFER = 2048; 

    //create the zipinputstream 
    ZipInputStream zis = new ZipInputStream(content); 

    //Get the name of the zip 
    String containerName = zipName; 

    //container for the zip entry 
    ZipEntry entry; 

    // Process each entry 
    while ((entry = zis.getNextEntry()) != null) { 

     //get the entry file name 
     String currentEntry = entry.getName(); 

     try { 

       ByteArrayOutputStream baos = new ByteArrayOutputStream(); 

       // establish buffer for writing file 
       byte data[] = new byte[BUFFER]; 
       int currentByte; 

       // read and write until last byte is encountered 
       while ((currentByte = zis.read(data, 0, BUFFER)) != -1) { 

        baos.write(data, 0, currentByte); 
       } 

       baos.flush(); //flush the buffer 

       //this method inserts the file into the database 
       insertZipEntry(baos.toByteArray()); 

       baos.close(); 

     } 
     catch (Exception e) { 
      System.out.println("ERROR WITHIN ZIP " + containerName); 
     } 
    } 
} 
+1

•您是否檢查過您嘗試處理的ZIP流(文件)是否有效(例如'unzip'可以解壓縮它)? •請確定實際產生異常的代碼行。 –

+1

我可能記得沒有正確,但是你不應該在處理它後關閉每個條目嗎? – biziclop

+0

您應該在調用insertZipEntry()之前關閉baos,並且我們的'currentByte'變量名稱很少:應該是'count'或類似的。 – EJP

回答

-1

千萬不要嘗試讀取比條目包含的字節更多的字節。調用ZipEntry.getSize()以獲取條目的實際大小,然後使用此值跟蹤條目中剩餘的字節數,同時讀取它。見下:

try{  

    ... 

    int bytesLeft = (int)entry.getSize(); 
    while (bytesLeft>0 && (currentByte=zis.read(data, 0, Math.min(BUFFER, bytesLeft))) != -1) { 
    ... 
    } 

    ... 

    } 
+0

這沒有必要。 ZipInputStream負責爲你服務。 – EJP

+0

EJP:但它失敗了。但是,entry.getSize()和entry.getCompressedSize()都返回-1。 – Buffalo

1

我會說你偶爾會被給予截斷的Zip文件來處理。上游檢查。