views:

30

answers:

2

Is it possible to create a Zip-Archive in Java if I do not want to write the resulting archive to disk but send it somewhere else?

The idea is that it might be a waste to create a file on disk when you want to send the Zip-Archive to a user via HTTP (e.g. from a Database-Blob or any other Data-Store).

I would like to create a

java.util.zip.ZipOutputStream 

or a

apache.commons.ZipArchiveOutputStream

where the Feeder would be a ByteArrayOutputStream coming from my Subversion Repository

+1  A: 

Yes this is absolutely possible!

Create your Zip entry using the putNextEntry method on the ZipOutputStream then put the bytes into the file in the zip by calling write on the ZipOutputStream. For the parameter for that method, the byte[], just extract them from the ByteArrayOutputStream with its toByteArray method.

And the ZipOutputStream can be sent anywhere, as its constructor just takes an OutputStream so could be e.g. your HTTP response.

Adrian Smith
Alright, that worked! But how do I create Directories that actually contain the files themselves then? Right now I get all files, fine, but the directories are unpacked as files with zero-byte length in the root node, so no hierarchy at all :-(
getagrip
ZIP files just contain a flat list of files. The file names, however, may contain path information. Just add a `ZipEntry` with a name such as `dir/file.txt`: that is `file.txt` within a directory `dir`.
Adrian Smith
Yes, by adding the absolute URL everything works a expected. Thank you very much!
getagrip
+1  A: 

Something like that would work:

ZipOutputStream zs = new ZipOutputStream(outputStream) ;
ZipEntry e = new ZipEntry(fileName);
zs.putNextEntry(e);
zs.write(...);
zs.close();
Eugene Kuleshov