[英]Write multiple Zip files to an OutputStream using IOUtils.copy method
這個問題感覺很難向我解釋,但我會盡力而為。
目前,我有一種方法可以返回帶有 Zip 文件的InputStream
,我必須將其添加到主 zip 文件中。 問題是當我在OutputStream
中寫入內容時,它會覆蓋以前寫入的數據。 我嘗試將ZipOutputStream
與ZipEntries
一起使用,但這會重新壓縮文件並做一些奇怪的事情,所以它不是一個解決方案。 我必須使用且不可協商的東西是:
使用返回 InputStream 的方法檢索文件
使用IOUtils.copy()
方法下載文件(如果您有另一個允許我通過瀏覽器下載文件的解決方案,這可能是可選的)
這是到目前為止的代碼:
OutputStream os = null;
InputStream is = null;
try {
os = response.getOutputStream();
for (int i = 0; i < splited.length; i += 6) {
String[] file= //an array with the data to retrieve the file
is = FileManager.downloadFile(args);
int read;
byte[] buffer = new byte[1024];
while (0 < (read = is.read(buffer))) {
os.write(buffer, 0, read);
}
}
} catch (Exception ex) {
//Exception captures
}
response.setHeader("Content-Disposition", "attachment; filename=FileName");
response.setContentType("application/zip");
IOUtils.copy(is, os);
os.close();
is.close();
return forward;
您可以使用 ZipOutputStream 包裝響應的 OutputStream,而不是 close 調用完成,並且不要在 ResponseOutputStream 上調用 close。
您必須從 HTTP 接頭開始。
response.setHeader("Content-Disposition", "attachment; filename=FileName");
response.setContentType("application/zip");
try {
ZipOutputStream os = new ZipOutputStream(response.getOutputStream());
for (int i = 0; i < splited.length - 5; i += 6) {
String[] file= //an array with the data to retrieve the file
try (InputStream is = FileManager.downloadFile(args)) {
os.putNextEntry(new ZipEntry(filePath));
is.TransferTo(os);
os.closeEntry();
}
}
os.finish();
} catch (Exception ex) {
//Exception captures
}
return forward;
自 java 9 transferTo
復制輸入/輸出流。 還可以使用Files.copy(Path, OutputStream)
復制Path
,其中Path
是基於 URI 的File
泛化,因此 URL 也可能立即被復制。
這里 try-with-resources 確保每一個is
關閉的。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.