2014-12-05 64 views
0

我有一個目錄,我用這種方法ZIP:輸出拉鍊目錄ByteArrayOutputStream

public byte[] archiveDir(File dir) { 
    try(ByteArrayOutputStream bos = new ByteArrayOutputStream(); ZipOutputStream zout = new ZipOutputStream(bos)) { 
     zipSubDirectory("", dir, zout); 
     return bos.toByteArray(); 
    } catch (IOException e) { 
     throw new RuntimeException(e); 
    } 
} 

private void zipSubDirectory(String basePath, File dir, ZipOutputStream zout) throws IOException { 
    byte[] buffer = new byte[4096]; 
    File[] files = dir.listFiles(); 
    for (File file : files) { 
     if (file.isDirectory()) { 
      String path = basePath + file.getName() + "/"; 
      zout.putNextEntry(new ZipEntry(path)); 
      zipSubDirectory(path, file, zout); 
      zout.closeEntry(); 
     } else { 
      FileInputStream fin = new FileInputStream(file); 
      zout.putNextEntry(new ZipEntry(basePath + file.getName())); 
      int length; 
      while ((length = fin.read(buffer)) > 0) { 
       zout.write(buffer, 0, length); 
      } 
      zout.closeEntry(); 
      fin.close(); 
     } 
    } 
} 

我然後寫入字節servlet的輸出流。但是,當我收到zip文件時,無法打開「文件格式錯誤」。如果我將壓縮內容輸出到FileOutputStream,然後將文件內容發送到servlet的輸出流,則它工作正常。那麼,這將解決我的問題,但在這種情況下,我將永遠不得不刪除它的內容發送到servlet的輸出流後的臨時zip文件。是否有可能只是在記憶中這樣做。

+0

「它無法打開」 - 這是什麼意思?你如何試圖打開它? – JimmyB 2014-12-05 11:41:28

+0

@HannoBinder它說,「該文件格式錯誤」。我更新了我的問題 – user1745356 2014-12-05 12:03:29

回答

2

嗯,

 zipSubDirectory(path, file, zout); 
     zout.closeEntry(); 

應該是:

 zout.closeEntry(); 
     zipSubDirectory(path, file, zout); 

主要錯誤似乎是ZOUT未關閉/之前沖刷toByteArray被調用。這裏嘗試與資源有點狡猾。

try (ByteArrayOutputStream bos = new ByteArrayOutputStream()) { 
    try ((ZipOutputStream zout = new ZipOutputStream(bos)) { 
     zipSubDirectory("", dir, zout); 
    } 
    return bos.toByteArray(); 
} catch (IOException e) { 
    throw new RuntimeException(e); 
} 
+0

這就像一個魅力。謝謝。 – user1745356 2014-12-05 12:16:07