4

我已经关注了这个主题,它非常有效。这是为文件下载器创建资源的功能

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

4

1 回答 1

1

这是我自己想出的解决方案

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"); 
}
于 2016-07-28T15:15:05.353 回答