Skip to Main Content

Java SE (Java Platform, Standard Edition)

Announcement

For appeals, questions and feedback about Oracle Forums, please email oracle-forums-moderators_us@oracle.com. Technical questions should be asked in the appropriate category. Thank you!

How to Create a Zip file from list of byte arrays on memory

843810Jul 28 2009 — edited Jul 29 2009
I want to zip a list of byte arrays in memory but not in file system. In all the examples and articles I could find have explained how this is done when the files are in file system. I could find only a .net example but not java one.

I have a list of objects specified below;
class FileToZip{
        String name;
        byte[] body;

        public FileToZip(String name, byte[] body) {
            super();
            this.name = name;
            this.body = body;
        }
}
I tried with below code to get the compressed byte[] which contains the byte arrays as compressed files in it. However this only adds the first file. Other files are not added in the final zip. Please help me if any one know how this can be done. I want to avoid creating temporary file becasue I just want to pass this as an attachment to create an email.
    private byte[] zip(String zipFileName, LinkedList<FileToZip> filesToZip){

    	ByteArrayOutputStream baos = new ByteArrayOutputStream();
	    
	    try {
	    	ZipOutputStream zos = new ZipOutputStream(baos);
	        for (Iterator<FileToZip> iter = filesToZip.iterator(); iter.hasNext();) {
	            FileToZip file =  iter.next();
	            ZipEntry entry = new ZipEntry(file.name);
	            entry.setSize(file.body.length);
	            zos.putNextEntry(entry);
	            zos.write(file.body);
	            zos.closeEntry();
	        }
	        zos.close();
	    } catch (IOException e) {
	    	log.debug("ERROR");
	    }
	    return baos.toByteArray();
    }
String attachmentName = abc.zip

EmailAttachment attachment = new EmailAttachment(
                attachmentName, 
                zip(attachmentName, filesToZip));
Appreciate any help on this...

Thank you.

Edited by: rmamila1 on Jul 28, 2009 12:06 AM

Edited by: rmamila1 on Jul 28, 2009 7:09 PM
Comments
Locked Post
New comments cannot be posted to this locked post.
Post Details
Locked on Aug 26 2009
Added on Jul 28 2009
2 comments
3,164 views