【问题标题】:How to create zip file with two outputStreams (working with JSF)如何使用两个输出流创建 zip 文件(使用 JSF)
【发布时间】:2014-03-06 16:57:25
【问题描述】:

我有两个输出流(由 jasper 报告填充数据以生成一个 excel 和一个 csv)。输出流的填充工作得很好,但现在我必须将两个“流/文件”打包到一个要下载的 zip 中。我怎么能这样做?

只下载一个文件的代码如下:

public void exportInternalEvaluation() {
    exportStats(ExportingValues.STATISTICS_INTERNAL_EVALUTATION, EXCEL_NAME, solvedDossiers,
            "application/vnd.ms-excel");
}

private void exportStats(ExportingValues exportingValues, String fileName, Collection < ? > collection,
        String contentType) {
    OutputStream os = null;
    try {
        FacesContext fc = FacesContext.getCurrentInstance();
        ExternalContext ec = fc.getExternalContext();

        ec.responseReset();
        ec.setResponseContentType(contentType);
        ec.setResponseHeader("Content-Disposition", "attachment; filename=\"" + fileName + "\"");
        os = ec.getResponseOutputStream();

        statsLocal.generateStatStream(collection, os, exportingValues.getJasperFileName(null),
                exportingValues.getReportingType());

        fc.responseComplete();
    } 
}

此代码将内容类型设置为 excel 并让我下载文件。我已经找到了以下内容:

        ZipOutputStream zos = new ZipOutputStream(os);  //create a zipOutputStream with my responseOutputStream

但后来我坚持创建ZipEntries。如何从 2 个不同的流中创建 2 个条目(1 个 excel 和 1 个 csv)?

编辑: 而且我真的不想创建 2 个临时文件并将它们添加到 zip 中。我想找到一种方法将 2 个输出流“添加”到一个 zip 文件中,创建 2 个不同的文件,而无需先创建它们(甚至是 tempFiles ..)。如果可能的话……

【问题讨论】:

    标签: java jsf-2 stream zip zipoutputstream


    【解决方案1】:

    您可以使用 ZipOutputStream 装饰响应流,并让生成器代码写入该响应流,以确保您在每次调用之间创建新条目:

    try (OutputStream os = ec.getResponseOutputStream();
        ZipOutputStream zout = new ZipOutputStream(os)) {
      zout.putNextEntry(new ZipEntry("foo.xls"));
      generate(zout, "Excell gen call args");
      zout.closeEntry();
      zout.putNextEntry(new ZipEntry("foo.csv"));
      generate(zout, "CSV gen call args");
      zout.closeEntry();
    }
    

    【讨论】:

    • 使用 java6 所以尝试资源在这里不起作用。但是您的解决方案似乎合法。如果它有效,将接受。
    猜你喜欢
    • 2013-08-27
    • 1970-01-01
    • 1970-01-01
    • 2010-09-22
    • 2013-02-23
    • 1970-01-01
    • 1970-01-01
    • 2021-12-18
    • 1970-01-01
    相关资源
    最近更新 更多