【问题标题】:creating zip file to byte array将 zip 文件创建为字节数组
【发布时间】:2014-04-29 15:57:03
【问题描述】:

我正在尝试从文件路径列表中读取创建一个 zip 文件。我想将 zip 文件作为字节数组,以便我可以将其作为 ResponseEntity 对象返回到网页。问题是当我尝试 FileOutputStream 时它可以工作。我试过 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();

对于您在上面看到的第一 2 行,如果我使用 ByteArrayOutputStream,则 zip 文件似乎已损坏。但如果我使用 FileOutputstream,我将无法打开 zip 文件及其内容。

这是我将 zip 字节数组发送回网页的方式。所有这些代码都发生在一个 spring 控制器方法中

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;

【问题讨论】:

    标签: java spring zip zipoutputstream


    【解决方案1】:

    看看 Google 的 GUAVA 库。它允许轻松复制Input to Output Streams。还要检查Apache Commons Compressspecial ZIP support

    但是,您也许可以让您的生活更轻松...
    HTTPResponse 有一个 OutputStream 对象。您应该获取该 OutputStream 并将其作为参数传递给您的 ZIP 创建函数,而不是通过函数混洗字节数组。这样您就可以避免需要所有内存来进行字节混洗以及它带来的潜在问题。

    希望有帮助!

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-01-12
      • 2018-02-16
      • 2021-10-09
      • 1970-01-01
      • 2011-04-11
      • 2014-11-16
      相关资源
      最近更新 更多