Java-DK Java-DK - 6 months ago 35
Java Question

Zip file created on server and download that zip, using java

I have the below code got from mkyong, to zip files on local. But, my requirement is to zip files on server and need to download that. Could any one help.

code wrote to zipFiles:

public void zipFiles(File contentFile, File navFile)
byte[] buffer = new byte[1024];

// i dont have idea on what to give here in fileoutputstream
FileOutputStream fos = new FileOutputStream("C:\\");
ZipOutputStream zos = new ZipOutputStream(fos);
ZipEntry ze= new ZipEntry(contentFile.toString());
FileInputStream in = new FileInputStream(contentFile.toString());

int len;
while ((len = > 0) {
zos.write(buffer, 0, len);


//remember close it


}catch(IOException ex){

what could i provide in fileoutputstream here? contentfile and navigationfile are files i created from code.


If your server is a servlet container, just write an HttpServlet which does the zipping and serving the file.

You can pass the output stream of the servlet response to the constructor of ZipOutputStream and the zip file will be sent as the servlet response:

ZipOutputStream zos = new ZipOutputStream(response.getOutputStream());

Don't forget to set the response mime type before zipping, e.g.:


The whole picture:

public class DownloadServlet extends HttpServlet {

    public void doGet( HttpServletRequest request, HttpServletResponse response ) throws ServletException, IOException {
        response.setHeader("Content-Disposition", "attachment;");

        // You might also wanna disable caching the response
        // here by setting other headers...

        try ( ZipOutputStream zos = new ZipOutputStream(response.getOutputStream()) ) {
            // Add zip entries you want to include in the zip file