2016-07-24 74 views
3

我遵循此topic,它完美的作品。這裏的功能爲文件下載器創建資源如何讓用戶使用vaadin文件下載器下載zip文件

private StreamResource createResource() { 
    return new StreamResource(new StreamSource() { 
     @Override 
     public InputStream getStream() { 
      String text = "My image"; 

      BufferedImage bi = new BufferedImage(100, 30, BufferedImage.TYPE_3BYTE_BGR); 
      bi.getGraphics().drawChars(text.toCharArray(), 0, text.length(), 10, 20); 

      try { 
       ByteArrayOutputStream bos = new ByteArrayOutputStream(); 
       ImageIO.write(bi, "png", bos); 
       return new ByteArrayInputStream(bos.toByteArray()); 
      } catch (IOException e) { 
       e.printStackTrace(); 
       return null; 
      } 

     } 
    }, "myImage.png"); 
} 

但我不知道如何使它創建一個zip文件的資源。我是否需要創建許多資源?謝謝

+0

解決方案壓縮-1565076.html)教程「壓縮和歸檔ZIP文件中的數據」部分。 –

+0

如果你想出了一個解決方案,請分享它作爲答案。 –

+0

誰是「他們」*? – specializt

回答

0

這裏如果你想使一個ZIP文件,按照[這](http://www.oracle.com/technetwork/articles/java/,我想通了,我自己

private StreamResource createZipResource() 
{ 
    return new StreamResource(new StreamSource() 
    { 
     @Override 
     public InputStream getStream() 
     { 
      ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); 

      try 
      { 
       ZipOutputStream out = new ZipOutputStream(byteArrayOutputStream); 

       for (int i = 0; i < listData.size(); i++) 
       { 
        if (listData.get(i).contains(".txt")) 
        { 
         out.putNextEntry(new ZipEntry(listData.get(i) + ".txt")); 
        } 
        else 
        { 
         out.write(listData.get(i).getBytes());        
        } 
       } 
       out.close(); 
       return new ByteArrayInputStream(byteArrayOutputStream.toByteArray()); 
      } 
      catch (IOException e) 
      { 
       System.out.println("Problem writing ZIP file: " + e); 
      } 
      return null; 
     } 
    },"Filename.zip"); 
}