Java Zip File List zipFiles(ArrayList files, String destZipFile)

Here you can find the source of zipFiles(ArrayList files, String destZipFile)

Description

zip Files

License

Apache License

Declaration

public static void zipFiles(ArrayList<File> files, String destZipFile) throws Exception 

Method Source Code


//package com.java2s;
//License from project: Apache License 

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

public class Main {
    public static void zipFiles(ArrayList<File> files, String destZipFile) throws Exception {
        if (files.size() > 0) {
            ZipOutputStream zip = null;
            FileOutputStream fileWriter = null;

            fileWriter = new FileOutputStream(destZipFile);
            zip = new ZipOutputStream(fileWriter);
            for (File f : files) {
                addFileToZip("", f.getAbsolutePath(), zip);
            }/*w  ww .j a  v a 2 s  . c  o  m*/

            zip.flush();
            zip.close();
            //         this.log.info("Zipped "+files.size()+" file(s) to "+ destZipFile);
        }

    }

    private static void addFileToZip(String path, String srcFile, ZipOutputStream zip) throws Exception {

        File folder = new File(srcFile);
        if (folder.isDirectory()) {
            addFolderToZip(path, srcFile, zip);
        } else {
            byte[] buf = new byte[1024];
            int len;
            FileInputStream in = new FileInputStream(srcFile);
            zip.putNextEntry(new ZipEntry(path + "/" + folder.getName()));
            while ((len = in.read(buf)) > 0) {
                zip.write(buf, 0, len);
            }
        }
    }

    private static void addFolderToZip(String path, String srcFolder, ZipOutputStream zip) throws Exception {
        File folder = new File(srcFolder);

        for (String fileName : folder.list()) {
            if (path.equals("")) {
                addFileToZip(folder.getName(), srcFolder + "/" + fileName, zip);
            } else {
                addFileToZip(path + "/" + folder.getName(), srcFolder + "/" + fileName, zip);
            }
        }
    }
}

Related

  1. zip(String[] filename, String outname)
  2. zip(String[] sFl, String sZip)
  3. zip(String[] sourceFiles, String zipFile, String directory)
  4. zip(String[] srcFiles, String dstFile, String comment)
  5. zipFileList(List files, File destinationDir)
  6. zipFiles(Collection resFileList, File zipFile)
  7. zipFiles(File file, JarOutputStream jos, String pathName)
  8. zipFiles(File output, File root, List fileList)
  9. zipFiles(File rootDir, File currDir, ZipOutputStream zos)