I want to archive some files that I am receiving from an external source. I receive each of this files as a ByteArrayInputStream. In the end I want my method to create the zip archive and return a byte[] array so that I can download it later. I have successfully managed to do this, but the end result is an ZipOutputStream and not the byte[] array that I need. Any ideeas are appreciated. Thanks!
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;
}
Copy to ByteArrayOutputStream
and then do baos.toByteArray()
to get your byte[]