Friday, August 28, 2009

How to create Zip File using Java

Java utils package provide class called ZipOutputStream which is used to write files to Zip format.

ZipEntry class is used to represent entry in Zip File.
getName() - used to get zip entry name
getMethod() - returns compression method of entry
getTime() - returns modification time
isDirectory() - returns true of entry is Directory entry
getCompressedSize() - returns compressed size of entry
getSize() - return uncompressed size of entry

One can create new ZipEntry and add it to ZipOutputStream.
Ex,
ZipEntry zipEntry = new ZipEntry(filesToZip);
/Add new Zip Entry to OutputStream
zipOutputStream.putNextEntry(zipEntry);


Java Program to create ZIP file using Java :
package com.anuj.utils;
package com.anuj.utils;

import java.io.*;
import java.util.zip.*;

public class ZipCreateExample {
 public static void main(String[] args) throws IOException {
  System.out.print("Please enter file name which will be added to zip : ");
  BufferedReader input = new BufferedReader(new InputStreamReader(System.in));
  String filesToZip = input.readLine();
  File f = new File(filesToZip);
  if (!f.exists()) {
   System.out.println("File not found.");
   System.exit(0);
  }
  
  String zipFileName = "output.zip";
  
  byte[] buffer = new byte[18024];
  
  try {
   FileOutputStream fileOutputStream = new FileOutputStream(zipFileName);
   ZipOutputStream zipOutputStream = new ZipOutputStream(fileOutputStream);
   //Set Level
   zipOutputStream.setLevel(Deflater.DEFAULT_COMPRESSION);
   
   FileInputStream in = new FileInputStream(filesToZip);
   
   //Create New Zip Entry
   ZipEntry zipEntry = new ZipEntry(filesToZip);
   //Add new Zip Entry to OutputStream
   zipOutputStream.putNextEntry(zipEntry);
   
   int len;
   while ((len = in.read(buffer)) > 0) {
    zipOutputStream.write(buffer, 0, len);
   }
   zipOutputStream.closeEntry();
   in.close();
   zipOutputStream.close();
  } catch (IllegalArgumentException iae) {
   iae.printStackTrace();
   System.exit(0);
  } catch (FileNotFoundException fnfe) {
   fnfe.printStackTrace();
   System.exit(0);
  } catch (IOException ioe) {
   ioe.printStackTrace();
   System.exit(0);
  }
 }
}


Author : Anuj Patel
Blog : http://goldenpackagebyanuj.blogspot.in/

No comments:

Post a Comment