I have generated many BufferedImages in memory and I want to compress them into one zip file before sending it as a email attachment. How do I save the files to a zip withou
I'm not sure about the use-case you're having here, if you have thousands of files in memory you might run out of memory rather quickly.
However, zip files are typically generated with streams anyway, so there's no need to temporarily store them in a file - might as well be in memory or streamed directly to a remote recipient (with only a small memory buffer to avoid a large memory footprint).
I found an old zip utility written years ago and modified it slightly for your use-case. It creates a zip file stored in a byte array from a list of files, also stored in byte arrays. Since you have a lot of files represented in memory, I added a small helper class MemoryFile
with just the filename and a byte array containing the contents. Oh, and I made the fields public to avoid the boilerplate getter/setter stuff - just to save some space here of course.
public class MyZip {
public static class MemoryFile {
public String fileName;
public byte[] contents;
}
public byte[] createZipByteArray(List<MemoryFile> memoryFiles) throws IOException {
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
ZipOutputStream zipOutputStream = new ZipOutputStream(byteArrayOutputStream);
try {
for (MemoryFile memoryFile : memoryFiles) {
ZipEntry zipEntry = new ZipEntry(memoryFile.fileName);
zipOutputStream.putNextEntry(zipEntry);
zipOutputStream.write(memoryFile.contents);
zipOutputStream.closeEntry();
}
} finally {
zipOutputStream.close();
}
return byteArrayOutputStream.toByteArray();
}
}
FileInputStream[] ins = //I assume you have all file handles in the form of FileInputStream
String[] fileNames = //I assume you have all file names
FileOutputStream out = new FileOutputStream(""); //specify the zip file name here
ZipOutputStream zipOut = new ZipOutputStream(out);
for (int i=0; i<ins.length; i++) {
ZipEntry entry = new ZipEntry(fileNames[i]);
zipOut.putNextEntry(entry);
int number = 0;
byte[] buffer = new byte[512];
while ((number = ins[i].read(buffer)) != -1) {
zipOut.write(buffer, 0, number);
}
ins[i].close();
}
out.close();
zipOut.close();
Based on the information you have provided, I come up with the code above. Hope this helps.