Sunday, May 6, 2007

Java|Create a zip file

Create a zip file : Zip Jar Tar : File Input Output : Java examples (example source code) Organized by topic

Create a zip file



import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

public class CreateZipFile {
  public static int BUFFER_SIZE = 10240 ;

  protected void createZipArchive(File archiveFile, File [] tobeZippedFiles) {
    try {
      byte buffer[] new  byte[BUFFER_SIZE];
      // Open archive file
      FileOutputStream stream = new FileOutputStream( archiveFile);
      ZipOutputStream out = new ZipOutputStream( stream);

      for (int i = 0 ; i < tobeZippedFiles.length; i++) {
        if (tobeZippedFiles[i== null || !tobeZippedFiles[i] .exists()
            || tobeZippedFiles[i].isDirectory ())
          continue;
        System.out.println("Adding " + tobeZippedFiles [i].getName());

        // Add archive entry
        ZipEntry zipAdd = new ZipEntry(tobeZippedFiles [i].getName());
        zipAdd.setTime(tobeZippedFiles[i ].lastModified());
        out.putNextEntry(zipAdd);

        // Read input & write to output
        FileInputStream in = new FileInputStream( tobeZippedFiles[i]);
        while (true) {
          int nRead = in.read(buffer, 0 , buffer.length);
          if (nRead <= 0)
            break;
          out.write(buffer, 0, nRead );
        }
        in.close();
      }

      out.close();
      stream.close();
      System.out.println("Adding completed OK") ;
    catch (Exception e) {
      e.printStackTrace();
      System.out.println("Error: " + e.getMessage ());
      return;
    }
  }
}

No comments: