Java-DK Java-DK - 29 days ago 11
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];

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

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

in.close();
zos.closeEntry();

//remember close it
zos.close();

System.out.println("Done");

}catch(IOException ex){
ex.printStackTrace();
}
}


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

Answer

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.:

response.setContentType("application/zip");

The whole picture:

public class DownloadServlet extends HttpServlet {

    @Override
    public void doGet( HttpServletRequest request, HttpServletResponse response ) throws ServletException, IOException {
        response.setContentType("application/zip");
        response.setHeader("Content-Disposition", "attachment; filename=data.zip");

        // 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
        }
    }
}