Java Zip File zip(File source, File target)

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

Description

zip

License

Apache License

Declaration

public static void zip(File source, File target) throws IOException 

Method Source Code


//package com.java2s;
/*//from www  . j  av a 2  s. c  o m
 * Copyright ? 2014 Stefan Niederhauser (nidin@gmx.ch)
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

import java.io.*;

import java.util.zip.ZipEntry;

import java.util.zip.ZipOutputStream;

public class Main {
    public static void zip(File source, File target) throws IOException {
        final ZipOutputStream out = new ZipOutputStream(new FileOutputStream(target));
        zip("", source, out);
        out.close();
    }

    private static void zip(String base, File source, ZipOutputStream target) throws IOException {
        final File[] files = source.listFiles();
        if (files != null) {
            for (final File file : files) {
                if (file.isDirectory()) {
                    final String fullName = base + file.getName() + "/";
                    target.putNextEntry(new ZipEntry(fullName));
                    target.closeEntry();
                    zip(fullName, file, target);
                } else {
                    target.putNextEntry(new ZipEntry(base + file.getName()));
                    copy(new FileInputStream(file), target, false);
                    target.closeEntry();
                }
            }
        }
    }

    private static void copy(InputStream in, OutputStream out, boolean closeOut) throws IOException {
        final byte[] buf = new byte[10000];
        int read;
        while ((read = in.read(buf)) > 0) {
            out.write(buf, 0, read);
        }
        in.close();
        if (closeOut) {
            out.close();
        }
    }
}

Related

  1. zip(File input, File output)
  2. zip(File input, File outputZip)
  3. zip(File inputDirectory, File zippedFile, FileFilter filter)
  4. zip(File path)
  5. zip(File source, File target)
  6. zip(File sourceDir, OutputStream targetStream)
  7. zip(File src, File target)
  8. zip(File srcDir, File zipFile)
  9. zip(File srcDirectory, File destFile)