如何为“虚拟文件”列表创建ZIP文件并输出到httpservletresponse [英] How to create ZIP file for a list of "virtual files" and output to httpservletresponse

查看:208
本文介绍了如何为“虚拟文件”列表创建ZIP文件并输出到httpservletresponse的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

My goal is to put multiple java.io.File objects into a zip file and print to HttpServletResponse for the user to download.

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

The files were created by the JAXB marshaller. It's a java.io.File object, but it's not actually on the file system (it's only in memory), so I can't create a FileInputStream.

所有资源我见过使用OutputStream打印zip文件内容。但是,所有这些资源都使用FileInputStream(我不能使用)。

All resources I've seen use the OutputStream to print zip file contents. But, all those resources use FileInputStream (which I can't use).

任何人都知道如何实现这个目标吗?

Anyone know how I can accomplish this?

推荐答案

原来我是个白痴:)正在创建的文件保存到无效路径并吞下异常,所以我认为它正在被创建好。但是,当我试图实例化一个新的FileInputStream时,它抱怨该文件不存在(这是正确的)。我有一个brainfart,并假设java.io.File对象实际上在某处包含文件信息。但正如埃里克森指出的那样,这是错误的。

Turns out I'm an idiot :) The file that was being "created" was saving to invalid path and swallowing the exception, so I thought it was being "created" ok. When I tried to to instantiate a new FileInputStream, however, it complained that file didn't exist (rightly so). I had a brainfart and assumed that the java.io.File object actually contained file information in it somewhere. But as erickson pointed out, that was false.

感谢Ralph的代码,我在解决了无效的路径问题后使用了它。

Thanks Ralph for the code, I used it after I solved the invalid pathing issue.

我的代码:

ZipOutputStream out = new ZipOutputStream(response.getOutputStream());
byte[] buf = new byte[1024];

File file;
InputStream in;
// Loop through entities
for (TitleProductAccountApproval tpAccountApproval : tpAccountApprovals) {
    // Generate the file    
    file = xmlManager.getXML(
        tpAccountApproval.getTitleProduct().getTitleProductId(), 
        tpAccountApproval.getAccount().getAccountId(), 
        username);

    // Write to zip file
    in = new FileInputStream(file);
    out.putNextEntry(new ZipEntry(file.getName()));

    int len;
    while ((len = in.read(buf)) > 0) {
        out.write(buf, 0, len);
    }

    out.closeEntry();
    in.close();
}

out.close();

这篇关于如何为“虚拟文件”列表创建ZIP文件并输出到httpservletresponse的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆