我已经按照这个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文件资源。我需要创建许多资源吗?谢谢
答案 0 :(得分: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");
}