将Outputstream转换为文件

时间:2013-07-05 11:21:14

标签: java html jsp pdf vraptor

好吧,我遇到了问题,

我需要使用html源创建PDF,我这样做:

File pdf = new File("/home/wrk/relatorio.pdf");
OutputStream out = new FileOutputStream(pdf);
InputStream input = new ByteArrayInputStream(build.toString().getBytes());//Build is a StringBuilder obj
Tidy tidy = new Tidy();
Document doc = tidy.parseDOM(input, null);
ITextRenderer renderer = new ITextRenderer();
renderer.setDocument(doc, null);
renderer.layout();
renderer.createPDF(out);
out.flush();
out.close();

我正在使用JSP,因此我需要将此文件下载给用户而不是在服务器中写入...

如何在不将此文件写入硬盘的情况下将此Outputstream输出转换为java中的文件?

3 个答案:

答案 0 :(得分:2)

如果您使用的是VRaptor 3.3.0+,则可以使用ByteArrayDownload课程。从代码开始,您可以使用:

@Path("/download-relatorio")
public Download download() {
    // Everything will be stored into this OutputStream
    ByteArrayOutputStream out = new ByteArrayOutputStream();

    InputStream input = new ByteArrayInputStream(build.toString().getBytes());
    Tidy tidy = new Tidy();
    Document doc = tidy.parseDOM(input, null);
    ITextRenderer renderer = new ITextRenderer();
    renderer.setDocument(doc, null);
    renderer.layout();
    renderer.createPDF(out);
    out.flush();
    out.close();

    // Now that you have finished, return a new ByteArrayDownload()
    // The 2nd and 3rd parameters are the Content-Type and File Name
    // (which will be shown to the end-user)
    return new ByteArrayDownload(out.toByteArray(), "application/pdf", "Relatorio.pdf");
}

答案 1 :(得分:0)

File对象实际上并不保存数据,而是将所有操作委托给文件系统(请参阅this discussion)。 但是,您可以使用File.createTempFile创建临时文件。如果不使用File对象,请查看here以获取可能的替代方案。

答案 2 :(得分:-1)

使用临时文件。

File temp = File.createTempFile(prefix ,suffix);

prefix - 前缀字符串定义文件名;必须至少三个字符。

后缀 - 后缀字符串定义文件的扩展名;如果为null,将使用后缀“.tmp”。