2014-04-29 132 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创建函数。这样可以避免需要所有内存进行字节混洗以及它带来的潜在问题。

希望有帮助!