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.

0 comments:

Post a Comment