How can I generate zip file without saving to the disk with Java?

后端 未结 2 443
盖世英雄少女心
盖世英雄少女心 2021-01-01 21:04

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

2条回答
  •  梦谈多话
    2021-01-01 21:45

    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 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();
        }
    
    }
    

提交回复
热议问题