How to create a zip file with Java and offer it for download

Share

In many web applications at some point a programmer meets the need to make an archive of a/some document(s) and offer this archive for download.
The main JAVA utilities for executing this archiving task are inside package java.util.zip.
These classes implement an output stream filter for writing files in the ZIP file format. They include support for both compressed and uncompressed entries.
The process of archiving document(s) is to read content as byte array from the original file(s), and then add the content to a java.util.zip.ZipOutputStream

1) Reading content as byte array:

a) The following section reads content from the filesystem:
For content reading, an input stream is added to the file for reading the data.

FileInputStream in = new FileInputStream(“C:/test/test.txt);
final byte[] buf = new byte[1024];
while ((len = in.read(buf)) > 0) { //Reads up to buf.length bytes of data from this input stream into an array of bytes
       out.write(buf, 0, len);
}

where out is a ZipOutputStream instance.

b)When dealing with WEBDAV
the content of a file can be obtained by using the GET command, which returns on response the content as byte array:

final DavGet get = new DavGet();
get.setResourcePath(“http://mydomain.com/repository/Project/test.txt”);
int response = get.execute();
content = get.getResponseDataBuffer();

These commands are found in the WEBDAV client API from different vendors.

2)add files for archiving

Each file can be added inside the archive with putNextEntry method. This method begins writing a new ZIP file entry and positions the stream to the start of the entry data. Also ,it closes the current entry if still active.

ZipOutputStream out = new ZipOutputStream(ouputStream);
out.putNextEntry(new ZipEntry(“filename”);

When dealing with multiple files inside an archive, this process of adding a nextEntry can be repeated for each of the files.

After adding all the files, the ZipOutputStream must be finished.

out.finish();
out.close();

Ok,so we created the archive.

3) Downloading this archive from a web browser

For this, the archive needs to be transmitted over a HTTP response.
If you have an application that is based on servlets all you have to do is to get the servlet outputstream and prepare it for handling a zip file. For this operation we need to set the right HTTP header for the response. See wikipedia for a list of possible headers that can be set both for request and response.
The HTTP response header we’ll use is Content-Disposition. This header’s description is ‘An opportunity to raise a “File Download” dialogue box for a known MIME type ‘. This means that the browser will automatically pop up an open/save dialog for the user when it meets this kind of header on response.
For setting the mime type of this content the content type header needs to be set as application/zip.
All in all, this means your servlet code must look something like this:

ServletOutputStream ouputStream;
try {
ouputStream = response.getOutputStream();
ZipOutputStream out = new ZipOutputStream(ouputStream);
out.putNextEntry(new ZipEntry(“filename”));
out.write(content);
response.setContentType("application/zip");
response.addHeader("Content-Disposition", "attachment; filename="+ archive_name"+".zip");
out.finish();
out.close();
} catch (IOException e) {
logger.error(e);
}

Do not forget to close the outputstream. Closing the output stream releases any system resources associated with this stream. A closed stream cannot perform output operations and cannot be reopened. This means that when closing, the response is sent, and now the browser should pop up the open/save dialog for downloading when the content disposition is set as ‘attachment’.

Finally, there’s another very important peculiarity of what does Cialis that brings it so high above its alternatives. It is the only med that is available in two versions – one intended for use on as-needed basis and one intended for daily use. As you might know, Viagra and Levitra only come in the latter of these two forms and should be consumed shortly before expected sexual activity to ensure best effect. Daily Cialis, in its turn, contains low doses of Tadalafil, which allows to build its concentration up in your system gradually over time and maintain it on acceptable levels, which, consequently, makes it possible for you to enjoy sex at any moment without having to time it.

By continuing to use the site, you agree to the use of cookies. More information

The cookie settings on this website are set to "allow cookies" to give you the best browsing experience possible. If you continue to use this website without changing your cookie settings or you click "Accept" below then you are consenting to this.

Close