2014-04-29 65 views
0

我想讀取從文件路徑列表中創建一個zip文件。我希望將zip文件作爲字節數組,以便我可以將它作爲ResponseEntity對象返回到網頁。問題是當我試圖FileOutputStream它的工作原理。我試過ByteArrayOutputStream壓縮文件已損壞。下面是一日2線您在上面看到,如果我使用ByteArrayOutputStream代碼創建zip文件到字節數組

//FileOutputStream bos = new FileOutputStream("C:\\files\\zipfile.zip"); 
ByteArrayOutputStream bos = new ByteArrayOutputStream(); 
ZipOutputStream zos = new ZipOutputStream(bos); 
ArrayList<String> filepaths = getAllFiles(); 
byte[] contents = null; 

for(String path : filepaths) { 
    File pdf = new File(path); 

    FileInputStream fis = new FileInputStream(pdf); 

    ZipEntry zipEntry = new ZipEntry(path.substring(path.lastIndexOf(File.separator)+1)); 
    zos.putNextEntry(zipEntry); 

    byte[] buffer = new byte[1024]; 
    int len; 
    while ((len = fis.read(buffer)) > 0) { 
     zos.write(buffer,0,len); 
    } 

    fis.close(); 
    zos.closeEntry(); 
    zos.flush(); 

} 
contents = new byte[bos.size()]; 
contents = bos.toByteArray(); 

zos.close(); 
bos.close(); 

,zip文件是似乎已損壞。但如果我使用FileOutputstream我無法打開zip文件及其內容。

這裏是我如何發回zip字節數組到網頁。所有這些代碼發生在彈簧控制器方法內

HttpHeaders headers = new HttpHeaders(); 
headers.setContentType(MediaType.parseMediaType("application/zip")); 
headers.setContentDispositionFormData(zipfileNm, zipfileNm); 

ResponseEntity<byte[]> response = new ResponseEntity<byte[]>(contents, headers, HttpStatus.OK); 
return response; 

回答

0

看看Google的GUAVA庫。它允許輕鬆複製Input to Output流。還可以用special ZIP support檢查Apache Commons Compress

但是,您可能可以使您的生活更輕鬆...
HTTPResponse具有OutputStream對象。而不是通過函數對字節數組進行混洗,您應該獲得OutputStream並將其作爲參數傳遞給ZIP創建函數。這樣可以避免需要所有內存進行字節混洗以及它帶來的潛在問題。

希望有幫助!