Wednesday, August 11, 2010

How create a zip file by Java

To write ZIP file, we use ZipOutputStream  class. For each file we want to put into the zip file, we create ZipEntry object and pass the file name to the ZipEntry constructor, it automatically sets other parameters such as file properties and decompression method. If you need to override these settings read Java API. Then we call the putNextEntry method of the ZipOutputStream to begin writing new file. Send the file data to the zip stream. After we close the Entry by calling closeEntry().

Here is the demonstration. I tested it and work like a charm.

//import classes
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.zip.*;

//Declaration of class Main
public class Main
{
  // Main method
  public static void main(String[] args)
  {
     //File path objects
     String source1 = "E:\\Pictures\\Elly\\elly1.jpg";
     String source2 = "E:\\Pictures\\Elly\\elly3.jpg";
     String source3 = "E:\\Pictures\\Elly\\elly5.jpg";

     //To create array
     String sources[] = {source1, source2, source3};

     //Create a buffer for reading files
     byte[] buf = new byte[1024];



     try
     {
         //To create target zip file
         String target = "E:\\target.zip";
         ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(target));

         for(int i=0;i 0)
             {
                 zos.write(buf, 0, len);
             }
             //complete Entry
             zos.closeEntry();
             zos.close();
         }
         //complete stream
         zos.close();

     }
     // catch Exceptions
     catch(IOException e)
     {
         System.out.println(e);
     }

  }
}

P.S
JAR files are simply ZIP files with another entry, the so-called manifest. You use the JarInputStream and JarOutputStream classes to read and write the manifest entry.

No comments:

Post a Comment