Tuesday, 24 June 2014

How to zip a file in java

java.util.zip.ZipOutputStream can be used to compress a file into ZIP format. Since a zip file can contain multiple entries, ZipOutputStream uses java.util.zip.ZipEntry to represent a zip file entry.

ZIP File

Creating a zip archive for a single file is very easy, we need to create a ZipOutputStream object from the FileOutputStream object of destination file. Then we add a new ZipEntry to the ZipOutputStream and use FileInputStream to read the source file to ZipOutputStream object. Once we are done writing, we need to close ZipEntry and release all the resources.

Zip Directory in Java

Zipping a directory is little tricky, first we need to get the files list as absolute path and then process each one of them separately. We need to add a ZipEntry for each file and use FileInputStream to read the content of the source file to the ZipEntry corresponding to that file.
Here is the java program showing how to zip a single file or zip a directory in java.

PROGRAM TO ZIP A SINGLE FILE

package com.krishna.zip;
 
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
 
public class App 
{ 
    public static void main( String[] args )
    {
     byte[] buffer = new byte[1024];
 
     try{
 
      FileOutputStream fos = new FileOutputStream("C:\\MyFile.zip");
      ZipOutputStream zos = new ZipOutputStream(fos);
      ZipEntry ze= new ZipEntry("spy.log");
      zos.putNextEntry(ze);
      FileInputStream in = new FileInputStream("C:\\spy.log");
 
      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();
     }
    }
}