I'm not sure if you have a precedent, if you have thousands of files in memory, you can quickly lose memory.
However, zip files are usually generated by streams anyway, so there is no need to temporarily store them in a file - it can also be in memory or transferred directly to a remote recipient (with a small memory buffer to avoid a large amount of memory).
I found an old zip utility written several years ago and modified it a bit 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 many files represented in memory, I added a small helper class, MemoryFile with just the file name and an array of bytes containing the contents. Oh, and I made the fields public to avoid working with templates / collectors - just to save 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(); } }
source share