Java Zip File zip(final File[] filesToZip, final File zipFile)

Here you can find the source of zip(final File[] filesToZip, final File zipFile)

Description

zip

License

Open Source License

Declaration

public static boolean zip(final File[] filesToZip, final File zipFile) 

Method Source Code

//package com.java2s;
//License from project: Open Source License 

import java.io.Closeable;

import java.util.zip.ZipOutputStream;
import java.io.FileOutputStream;

import java.io.IOException;

import java.io.FileInputStream;

import java.util.zip.ZipEntry;

import java.io.File;

public class Main {
    public static boolean zip(final File[] filesToZip, final File zipFile) {
        final byte[] buf = new byte[2048];
        ZipOutputStream out = null;
        FileInputStream in = null;
        try {//  w  ww. java 2s.c  om
            out = new ZipOutputStream(new FileOutputStream(zipFile));
            for (int i = 0; i < filesToZip.length; ++i) {
                in = new FileInputStream(filesToZip[i]);
                out.putNextEntry(new ZipEntry(filesToZip[i].getName()));
                int len;
                while ((len = in.read(buf)) != -1) {
                    out.write(buf, 0, len);
                }
                out.closeEntry();
                in.close();
            }
            out.close();
        } catch (IOException e) {
            System.err.println("Can't zip()");
            e.printStackTrace();
            safeClose(out);
            safeClose(in);
            return false;
        }
        return true;
    }

    public static <S extends Closeable> void safeClose(final S s) {
        if (s == null) {
            return;
        }
        try {
            s.close();
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }
}

Related

  1. zip(File[] sourceFiles, File destFile, boolean deleteOriginalFiles)
  2. zip(final File dir, final File target)
  3. zip(final File tempLocation, final File targetZipFile)
  4. zip(final File zipFile, final File... files)
  5. zip(final File zipFile, final File[] files)
  6. zip(final Map files)
  7. zip(final String fileName, final byte[] fileContent)
  8. zip(final String sourceFileDir, final String zipFile)
  9. zip(InputStream is)