如何让用户使用vaadin文件下载器下载zip文件

我跟着这个
topic,它完美无缺.这是为文件下载器创建资源的功能

 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文件的资源.我需要创建许多资源吗?谢谢

最佳答案 这是我自己想出来的解决方案

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"); 
}
点赞