Java Zip File zip(File input, File outputZip)

Here you can find the source of zip(File input, File outputZip)

Description

zip

License

Open Source License

Declaration

public static void zip(File input, File outputZip) throws IOException 

Method Source Code


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

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

public class Main {
    public static void zip(File input, File outputZip) throws IOException {
        zip(input, new FileOutputStream(outputZip), false, null);
    }/*from   w  w w .ja  v  a 2s  . c  o  m*/

    public static void zip(File input, OutputStream output, boolean withHidden, Set<String> excludeEntries)
            throws IOException {
        if (!input.exists())
            throw new IOException("File doesn't exist: " + input);
        ZipOutputStream zos = null;
        try {
            zos = new ZipOutputStream(output);
            addToZip(input, "", zos, withHidden, excludeEntries);
        } finally {
            try {
                if (zos != null)
                    zos.close();
            } catch (Exception ignore) {
            }
        }
    }

    private static void addToZip(File input, String entryName, ZipOutputStream zos, boolean withHidden,
            Set<String> excludeEntries) throws IOException {
        if (input.isHidden() && !withHidden)
            return;
        if (input.isDirectory()) {
            if (entryName.length() > 0)
                entryName += "/";
            for (File f : input.listFiles())
                addToZip(f, entryName + f.getName(), zos, withHidden, excludeEntries);
        } else if (input.isFile()) {
            if (excludeEntries != null && excludeEntries.contains(entryName))
                return;
            FileInputStream fis = null;
            try {
                byte[] buffer = new byte[10000];
                fis = new FileInputStream(input);
                zos.putNextEntry(new ZipEntry(entryName));
                int length;
                while ((length = fis.read(buffer)) > 0)
                    zos.write(buffer, 0, length);
                zos.closeEntry();
            } finally {
                try {
                    if (fis != null)
                        fis.close();
                } catch (Exception ignore) {
                }
            }
        }
    }
}

Related

  1. zip(File file, File output)
  2. zip(File file, File zip)
  3. zip(File file, String dest)
  4. zip(File fromFile, File toFile)
  5. zip(File input, File output)
  6. zip(File inputDirectory, File zippedFile, FileFilter filter)
  7. zip(File path)
  8. zip(File source, File target)
  9. zip(File source, File target)