tags:

views:

3479

answers:

3

My application is receiving email through SMTP server. There are one or more attachments in the email and email attachment return as byte[] (using sun javamail api).

I am trying to zip the attachment files on the fly without writing them to disk first.

What is/are possible way to achieve this outcome?

A: 

Maybe the java.util.zip package might help you

Since you're asking about how to convert from byte array I think (not tested) you can use the ByteArrayInputStream method

int     read(byte[] b, int off, int len)
          Reads up to len bytes of data into an array of bytes from this input stream.

that you will feed to

ZipInputStream  This class implements an input stream filter for reading files in the ZIP file format.
Eric
A: 

You have to use a ZipOutputStream for that.

http://java.sun.com/javase/6/docs/api/java/util/zip/ZipOutputStream.html

OscarRyz
+12  A: 

You can use Java's java.util.zip.ZipOutputStream to create a zip file in memory. For example:

public static byte[] zipBytes(String filename, byte[] input) throws IOException {
 ByteArrayOutputStream baos = new ByteArrayOutputStream();
 ZipOutputStream zos = new ZipOutputStream(baos);
 ZipEntry entry = new ZipEntry(filename);
 entry.setSize(input.length);
 zos.putNextEntry(entry);
 zos.write(input);
 zos.closeEntry();
 zos.close();
 return baos.toByteArray();
}
Dave L.