Create Zip File From Directory Recursively Using ZipOutputStream - Java File Path IO

Java examples for File Path IO:ZipOutputStream

Description

Create Zip File From Directory Recursively Using ZipOutputStream

Demo Code

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

public class Main {

  public static void main(String args[]) {
    String sourceDir = "C:/examples";
    String zipFile = "C:/Folder/zipdemo.zip";

    try {//from  www.jav  a 2s.  c o  m
      FileOutputStream fout = new FileOutputStream(zipFile);
      ZipOutputStream zout = new ZipOutputStream(fout);
      File fileSource = new File(sourceDir);
      addDirectory(zout, fileSource);
      zout.close();
      System.out.println("Zip file has been created!");

    } catch (IOException ioe) {
      System.out.println("IOException :" + ioe);
    }
  }

  private static void addDirectory(ZipOutputStream zout, File fileSource) {
    File[] files = fileSource.listFiles();

    System.out.println("Adding directory " + fileSource.getName());

    for (int i = 0; i < files.length; i++) {
      if (files[i].isDirectory()) {
        addDirectory(zout, files[i]);
        continue;
      }
      try {
        System.out.println("Adding file " + files[i].getName());
        byte[] buffer = new byte[1024];

        // create object of FileInputStream
        FileInputStream fin = new FileInputStream(files[i]);

        zout.putNextEntry(new ZipEntry(files[i].getName()));

        int length;

        while ((length = fin.read(buffer)) > 0) {
          zout.write(buffer, 0, length);
        }

        zout.closeEntry();

        fin.close();

      } catch (IOException ioe) {
        System.out.println("IOException :" + ioe);
      }
    }
  }
}

Related Tutorials