Friday 20 July 2012

Create zip file in Java

In this section, you will learn about how to create a zip file from any file through the java program.A Zip file is a compressed format file and takes less space then the original file. Many files which are available for download on the internet are stored to a "ZIP" file. When the original files are needed, the user can "extract" the original files from the ZIP file using a ZIP file program.


The java.util.zip.ZipOutputStream can be used to compress data to a ZIP file. The ZipOutputStream writes data to an output stream in a ZIP format.

There are a number of steps involved in creating a ZIP file.

Step: 1


The first step is to create a ZipOutputStream object, to which we pass the output stream of the file we wish to write to. Here is how you create a ZIP file entitled "myfiles.zip":


FileOutputStream dest = new
  FileOutputStream("myfiles.zip");
ZipOutputStream out = new
  ZipOutputStream(new BufferedOutputStream(dest));


Step: 2


Once the target zip output stream is created, the next step is to open the source data file. In this example, source data files are those files in the specified directory. The listFiles() command is used to get a list of files in the given directory:


File f = new File("directoryPath");
File files[] = f.listFiles();
for (int i=0; i<files.length; i++) {
   System.out.println("Adding: "+files[i]);
   FileInputStream fi = new FileInputStream(files[i]);
   // create zip entry
   // add entries to ZIP file
}


Note: This code sample is capable of compressing all files in the specified directory. It doesn't handle sub directories.


Step: 3


Create a zip entry for each file that is read:


ZipEntry entry = new ZipEntry(files[i]))


Step: 4


Before you can write data to the ZIP output stream, you must first put the zip entry object using the putNextEntry method:


out.putNextEntry(entry);


Step: 5


Write the data to the ZIP file and close the source stream:
int count;
while((count = fi.read(data, 0, BUFFER)) != -1) {
   out.write(data, 0, count);
}
fi.close();


Step: 6


Finally, you close the output stream:
out.close();


The complete source code is given below:


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

public class Zip {
 static final int BUFFER = 2048;

 /**
  * Command line arguments :
  * argv[0]-----> Source directory. 
  * argv[1]-----> Destination zip file.
  **/
 public static void main(String argv[]) {
  try {

   BufferedInputStream origin = null;

   /** Step: 1 ---> create a ZipOutputStream object. **/

   FileOutputStream dest = new FileOutputStream(argv[1]);
   ZipOutputStream out = new ZipOutputStream(new BufferedOutputStream(
     dest));

   // out.setMethod(ZipOutputStream.DEFLATED);
   byte data[] = new byte[BUFFER];

   /**
    * Step: 2 --->Open the source data and get a list of files from
    * given directory.
    **/

   File source = new File(argv[0]);
   if (!source.exists()) {
    System.out.println("Input directory does not exist..");
    System.exit(0);
   }
   File files[] = source.listFiles();

   for (int i = 0; i < files.length; i++) {

    System.out.println("Adding File: "
      + source.getParentFile().toURI()
        .relativize(files[i].toURI()).getPath());

    FileInputStream fi = new FileInputStream(files[i]);

    origin = new BufferedInputStream(fi, BUFFER);

    /** Step: 3 ---> Create a zip entry for each file that is read. **/

    /**
     * relativize is used to to add a file to a zip, without
     * including the entire path from root.
     **/

    ZipEntry entry = new ZipEntry(source.getParentFile().toURI()
      .relativize(files[i].toURI()).getPath());

    /** Step: 4 ---> Put the zip entry using putNextEntry. **/

    out.putNextEntry(entry);

    /**
     * Step: 5 ---> Write the data to the ZIP file and close the
     * input stream.
     **/

    int count;
    while ((count = origin.read(data, 0, BUFFER)) != -1) {
     out.write(data, 0, count);
    }
    origin.close();
   }

   /** Step: 6 --->close the output stream. **/

   out.close();
   System.out.println("Zip file created successfully!!");
  } catch (Exception e) {
   e.printStackTrace();
  }
 }
}
Note: Entries can be added to a ZIP file either in a compressed (DEFLATED) or uncompressed (STORED) form. The setMethod can be used to set the method of storage. For example, to set the method to DEFLATED (compressed) use: out.setMethod(ZipOutputStream.DEFLATED) and to set it to STORED (not compressed) use: out.setMethod(ZipOutputStream.STORED).

Create Zip File From Directory Recursively Using ZipOutputStream in Java


No comments:

Post a Comment