Create ZIP File using Java Code



Create ZIP File using Java Code



We seen how to unzip a ZIP file using Java code in our earlier tutorial, now we will see how to create a ZIP file using Java code in this tutorial. Below sample code will read list of files in a folder and zip file name as input parameters. 



import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
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 void main(String argv[]) {
  // List of files in a folder to zip
  String filesPath = "D:\\filesfolder";
  // ZIP file name and path to create
  String zipFileName = "D:\\myZipFile.zip";
  
  createZIPFile(filesPath, zipFileName);
 }
 
 public static void createZIPFile(String filesPath, String zipFileName){

  try {
  
   FileOutputStream dest = new FileOutputStream(zipFileName);
   ZipOutputStream out = new ZipOutputStream(new BufferedOutputStream(dest));

   byte buffer[] = new byte[1024];
   File file = new File(filesPath);
   String files[] = file.list();
   System.out.println("No. of files to ZIP : "+files.length);
   BufferedInputStream bis = null;
   for (int i = 0; i < files.length; i++) {
    FileInputStream fi = new FileInputStream(filesPath+ "\\"+ files[i]);
    bis = new BufferedInputStream(fi, 1024);
    ZipEntry entry = new ZipEntry(files[i]);
    out.putNextEntry(entry);
    int count;
    while ((count = bis.read(buffer, 0, 1024)) != -1) {
     out.write(buffer, 0, count);
    }
    bis.close();
   }
   out.close();
  } catch (Exception e) {
   e.printStackTrace();
  }
 }
}









No comments :

Post a Comment