Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create Java-Zip-Archive from existing OutputStream

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

like image 654
trajectory Avatar asked Oct 25 '10 16:10

trajectory


People also ask

How do you make a zip file with Java?

Creating a zip archive for a single file is very easy, we need to create a ZipOutputStream object from the FileOutputStream object of destination file. Then we add a new ZipEntry to the ZipOutputStream and use FileInputStream to read the source file to ZipOutputStream object.

How do you write ZipOutputStream to a file?

write(byte[] buf, int off, int len) method writes an array of bytes to the current ZIP entry data. This method will block until all the bytes are written.


2 Answers

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.

like image 142
Adrian Smith Avatar answered Oct 05 '22 21:10

Adrian Smith


Something like that would work:

ZipOutputStream zs = new ZipOutputStream(outputStream) ;
ZipEntry e = new ZipEntry(fileName);
zs.putNextEntry(e);
zs.write(...);
zs.close();
like image 32
Eugene Kuleshov Avatar answered Oct 05 '22 19:10

Eugene Kuleshov