我想從S3等外部源下載多個文件,創建一個包含所有這些文件的zip
文件,並向用戶提供一個鏈接以下載該文件zip
文件。使用Java將多個文件並行下載到S3中的zip文件
很顯然,我可以按順序處理文件,讀取每個文件的輸入流並將其寫入ZipOutputStream
。
如何並行讀取所有輸入文件流並寫入單個輸出流,以便我可以向用戶展示下載鏈接,而不必等到zip
文件完全寫入?
我當前的代碼:
String realpath = getServletContext().getRealPath("/");
response.setContentType("application/zip");
response.setHeader("Content-Disposition","attachment; filename="+fi.replace('/', '-')+"_"+ff.replace('/', '-')+".zip");
ServletOutputStream out = null;
ZipOutputStream zipfile = null;
try
{
List<Object[]> cfdis = /*my hibernate criteria source, your Database?*/
out = response.getOutputStream();
zipfile = new ZipOutputStream(out);
ZipEntry zipentry = null;
for(Object[] cfdi:cfdis)
{
zipentry = new ZipEntry(cfdi[1].toString()+".xml");
zipfile.putNextEntry(zipentry);
InputStream in = new FileInputStream(new File(realpath+cfdi[0].toString()));
byte[] bytes = new byte[FILEBUFFERSIZE];
int bytesRead;
while ((bytesRead = in.read(bytes)) != -1)
{
zipfile.write(bytes, 0, bytesRead);
}
}
@Muhammadismail而不是將代碼放在評論中,請編輯您的問題,並在其中包含代碼。 – Cinnam
希望我已經解決了這個問題。 – wOxxOm
非常感謝@wOxxOm –