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