微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

java – 如何为“虚拟文件”列表创建ZIP文件并输出到httpservletresponse

我的目标是将多个java.io.File对象放入zip文件并打印到HttpServletResponse以供用户下载.

这些文件是由JAXB marshaller创建的.它是一个java.io.File对象,但它实际上不在文件系统上(它只在内存中),因此我无法创建FileInputStream.

我见过的所有资源都使用OutputStream来打印zip文件内容.但是,所有这些资源都使用FileInputStream(我无法使用).

谁知道我怎么能做到这一点?

最佳答案
看看Apache Commons Compress库,它提供了您需要的功能.

当然,“erickson”对你的问题发表评论是正确的.您将需要文件内容而不是java.io.File对象.在我的例子中,我假设你有一个方法
byte [] getTheContentFormSomewhere(int fileNummer),它返回fileNummer-th文件文件内容(在内存中). – 当然这个功能设计很差,但它仅用于说明.

它应该有点像这样:

void compress(final OutputStream out) {
  ZipOutputStream zipOutputStream = new ZipOutputStream(out);
  zipOutputStream.setLevel(ZipOutputStream.STORED);

  for(int i = 0; i < 10; i++) {
     //of course you need the file content of the i-th file
     byte[] oneFileContent = getTheContentFormSomewhere(i);
     addOneFiletoZipArchive(zipOutputStream,"file"+i+"."txt",oneFileContent);
  }

  zipOutputStream.close();
}

void addOneFiletoZipArchive(final ZipOutputStream zipStream,String fileName,byte[] content) {
    ZipArchiveEntry zipEntry = new ZipArchiveEntry(fileName);
    zipStream.putNextEntry(zipEntry);
    zipStream.write(pdfBytes);
    zipStream.closeEntry();
}

你的http控制器的Snipets:

HttpServletResponse response
...
  response.setContentType("application/zip");
  response.addheader("Content-disposition","attachment; filename=\"compress.zip\"");
  response.addheader("Content-transfer-encoding","binary");
  ByteArrayOutputStream outputBuffer = new ByteArrayOutputStream();
  compress(outputBuffer);
  response.getoutputStream().write(outputBuffer.toByteArray());
  response.getoutputStream().flush();
  outputBuffer.close();

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐