我想使用 JaxRS 从我的服务器创建并返回一个 zip 文件。我不认为我想在服务器上创建一个实际的文件,如果可能的话,我想动态创建 zip 并将其传递回客户端。如果我即时创建一个巨大的 zip 文件,如果 zip 文件中有太多文件,我会耗尽内存吗?
我也不确定最有效的方法。这就是我的想法,但是当涉及到 java 中的输入/输出时,我非常生疏。
public Response getFiles() {
// These are the files to include in the ZIP file
String[] filenames = // ... bunch of filenames
byte[] buf = new byte[1024];
try {
// Create the ZIP file
ByteArrayOutputStream baos= new ByteArrayOutputStream();
ZipOutputStream out = new ZipOutputStream(new BufferedOutputStream(baos));
// Compress the files
for (String filename : filenames) {
FileInputStream in = new FileInputStream(filename);
// Add ZIP entry to output stream.
out.putNextEntry(new ZipEntry(filename));
// Transfer bytes from the file to the ZIP file
int len;
while ((len = in.read(buf)) > 0) {
out.write(buf, 0, len);
}
// Complete the entry
out.closeEntry();
in.close();
}
// Complete the ZIP file
out.close();
ResponseBuilder response = Response.ok(out); // Not a 100% sure this will work
response.type(MediaType.APPLICATION_OCTET_STREAM);
response.header("Content-Disposition", "attachment; filename=\"files.zip\"");
return response.build();
} catch (IOException e) {
}
}
任何帮助将不胜感激。