2014-03-06 41 views
1

我有兩個輸出流(由jasper報告填充數據以生成一個excel和一個csv)。輸出流的填充工作正常,但現在我必須將「流/文件」打包到要下載的壓縮文件中。我怎麼能這樣做?如何使用兩個outputStreams(使用JSF)創建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(); 
    } 
} 

此代碼設置內容類型脫穎而出,讓我下載的文件。我已經發現以下內容:

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

但後來我被卡在創建ZipEntries。我如何從2個不同的流創建2個條目(1個excel和1個csv)?

編輯: 我並不想創建2個臨時文件並將它們添加到壓縮文件中。我想找到一種方法將2個輸出流「添加」到一個壓縮文件,創建2個不同的文件,而無需先創建它們(即使是tempFiles ..)。如果可能的話,雖然...

回答

0

您可以用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(); 
} 
+0

使用的Java6有這麼嘗試資源在這裏不起作用。但你的解決方案似乎合法。將接受,如果它的工作。 – GregD