Friday, January 15, 2010

Creating a zip file

Creating a zip file in Java web application may appear to be a difficult task, but thanks to Java which comes bundled with many packages and classes which provide many useful utilities, tools and methods. One such package is the "java.util.zip" package which provides various classes and methods to manage zip files.

Following is an extract of code from a Servlet which can be customized and used to create zip files.


import java.util.zip.*;

// These are the files to include in the ZIP file
java.util.Set fileNames = new java.util.TreeSet () ; 

fileNames.add(csvFileName);
// add multiple files as above

/*
 * Creating a ZIP File
 */
     
  // Create a buffer for reading the files
  byte[] buf = new byte[1024];
  String outFilename="";
  fileName="";
  try 
  {
     // Create the ZIP file
     outFilename = getServletContext().getRealPath("/insurance") + "/" + "insurance.zip";
     ZipOutputStream zipOut = new ZipOutputStream(new FileOutputStream(outFilename));
     
     // Compress the files
     for(String str : fileNames)
     {
         FileInputStream in = new FileInputStream(str);
    
         // Add ZIP entry to output stream.
         fileName = str;
         fileName = fileName.substring(fileName.lastIndexOf("/") + 1);
         zipOut.putNextEntry(new ZipEntry(fileName));
     
         // Transfer bytes from the file to the ZIP file
         int len;
         while ((len = in.read(buf)) > 0) 
            zipOut.write(buf, 0, len);
  
         // Complete the entry
         zipOut.closeEntry();
         in.close();
     }
     
     // Complete the ZIP file
     zipOut.close();
  }
  catch(java.util.zip.ZipException ex)
  {
      System.out.println("InsuranceReportArtistWiseServ:ZipException:creating zip\n"+ex);
  }
  catch(IOException ex) 
  {
      System.out.println("InsuranceReportArtistWiseServ:IOException:creating zip\n"+ex);
  }

  /*
   * Clean up - zip file ready to download, now delete all csv files
   */
    boolean success=false;
    for(String str : fileNames)
    {
    success = (new java.io.File(str)).delete();
    }
Now the "insurace.zip" file is ready to be sent as a download to the user.

Sending a file as a download using Java

Many times it may be a requirement to send a file from a server to a user as a download which can be saved on the users machine. To send a file as a download to a user all you need is a Servlet and the file which will be sent to the user. Below is a sample code for the Servlet which will send a file as a download.

private static javax.servlet.ServletConfig config;

/* (non-Javadoc)
 * @see javax.servlet.GenericServlet#init(javax.servlet.ServletConfig)
 */
@Override
public void init(ServletConfig config) throws ServletException 
{
    // TODO Auto-generated method stub
    super.init(config);
    FileDownloadServ.config = config;
}

private void sendFile(String fileName, HttpServletRequest request, HttpServletResponse response)
{
  java.io.File f = null;
  String file;
  
  file = FileDownloadServ.config.getServletContext().getRealPath("/" + fileName);
  f = new java.io.File(file);

  int length = 0;
  javax.servlet.ServletOutputStream op=null; 
  try
  {
      op = response.getOutputStream();
  }
  catch(java.io.IOException ex)
  {
      System.out.println("IOException while opening the output stream\n"+ex);
  } 

  javax.servlet.ServletContext context  = getServletConfig().getServletContext();
  String mimetype = "application/octet-stream";
  response.setContentType(mimetype);
  response.setContentLength( (int)f.length() );

  response.setHeader("Content-Disposition", "attachment; filename=\"" + fileName + "\"" );
  //
  //  Stream to the requester.
  //
  byte[] bbuf = new byte[1024];
  try
  {
     java.io.DataInputStream in = new java.io.DataInputStream(new java.io.FileInputStream(f));

     while ((in != null) && ((length = in.read(bbuf)) != -1))
     {
      op.write(bbuf,0,length);
     }

     in.close();
     op.flush();
     op.close();
  }
  catch(java.io.IOException ex)
  {
     System.out.println("IOException while reading file!\n"+ex);
  }
}     

The above method when called from a Servlet's doPost() or doGet() with fileName as parameter will sent the file to the user.