Create Zip File From Multiple Files using ZipOutputStream - Java File Path IO

Java examples for File Path IO:ZipOutputStream

Description

Create Zip File From Multiple Files using ZipOutputStream

Demo Code


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[]) {
    try {//from  w ww .  j a  va2 s  .  c om
      String zipFile = "C:/Folder/zipdemo.zip";
      String[] sourceFiles = { "C:/file1.doc", "C:/file2.doc" };
      byte[] buffer = new byte[1024];
      FileOutputStream fout = new FileOutputStream(zipFile);
      ZipOutputStream zout = new ZipOutputStream(fout);
      for (int i = 0; i < sourceFiles.length; i++) {
        System.out.println("Adding " + sourceFiles[i]);
        FileInputStream fin = new FileInputStream(sourceFiles[i]);
        zout.putNextEntry(new ZipEntry(sourceFiles[i]));
        int length;

        while ((length = fin.read(buffer)) > 0) {
          zout.write(buffer, 0, length);
        }
        zout.closeEntry();
        fin.close();
      }
      zout.close();
      System.out.println("Zip file has been created!");
    } catch (IOException ioe) {
      System.out.println("IOException :" + ioe);
    }

  }
}

Result


Related Tutorials