加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 大数据 > 正文

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

发布时间:2020-12-15 01:36:58 所属栏目:大数据 来源:网络整理
导读:我的目标是将多个java.io.File对象放入zip文件并打印到HttpServletResponse以供用户下载. 这些文件是由JAXB marshaller创建的.它是一个java.io.File对象,但它实际上不在文件系统上(它只在内存中),因此我无法创建FileInputStream. 我见过的所有资源都使用Outp

我的目标是将多个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();

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读