我想归档一些我从外部来源收到的文件。我将每个文件作为ByteArrayInputStream接收。最后,我希望我的方法能够创建 zip 存档并返回一个 byte[] 数组,以便稍后下载。我已经成功地做到了这一点,但最终结果是一个 ZipOutputStream 而不是我需要的 byte[] 数组。任何想法表示赞赏。谢谢!
FileOutputStream fos = null;
ZipOutputStream zipOut = null;
try {
fos = new FileOutputStream(archiveFileName.concat(ReportFormat.ZIP.getFileExtension()));
zipOut = new ZipOutputStream(new BufferedOutputStream(fos));
for (Map.Entry<?, ByteArrayInputStream> entry : mapInputStream.entrySet()) {
String fileFromInsiteArchiveName = (String) entry.getKey();
ByteArrayInputStream inputStream = entry.getValue();
ZipEntry zipEntry = new ZipEntry(fileFromInsiteArchiveName);
zipOut.putNextEntry(zipEntry);
byte[] tmp = new byte[4 * 1024];
int size = 0;
while ((size = inputStream.read(tmp)) != -1) {
zipOut.write(tmp, 0, size);
}
zipOut.flush();
inputStream.close();
}
zipOut.close();
return zipOut;
} catch (FileNotFoundException e) {
//handle this
} catch (IOException e) {
//handle this
} finally {
try {
if (fos != null) fos.close();
} catch (Exception ex) {
//handlethis
}
}
return zipOut;
}