Showing posts with label zip. Show all posts
Showing posts with label zip. Show all posts

Friday, May 15, 2015

Create Zip File Using Java From List Of Files


package com.pkm.zip;

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

public class Main {
    public static void main(String[] args) throws Exception {
         List<String> fileList = new ArrayList<>();
         fileList.add("ImageName.png");
         fileList.add("ImageName.jpg");
         fileList.add("ImageName.gif");
         createZip(fileList, "Output.zip");
    }

    public static void createZip(List<String> fileList, String zipFileName) 
              throws Exception {
         FileOutputStream fileOutputStream = new FileOutputStream(zipFileName);
         ZipOutputStream zipOutputStream = new ZipOutputStream(fileOutputStream);
  
         for(String inputFileName : fileList) {
             File file = new File(inputFileName);
             FileInputStream fileInputStream = new FileInputStream(file);
             ZipEntry zipEntry = new ZipEntry(inputFileName);
             zipOutputStream.putNextEntry(zipEntry);

             byte[] bytes = new byte[1024];
             int length;
             while ((length = fileInputStream.read(bytes)) >= 0) {
                 zipOutputStream.write(bytes, 0, length);
             }

             zipOutputStream.closeEntry();
             fileInputStream.close();
         }
  
         zipOutputStream.close();
         fileOutputStream.close();
    }
}