Java Zip Directory zip(File directory, File zipFile)

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

Description

Zip.

License

Open Source License

Parameter

Parameter Description
directory the directory
zipFile the zip file

Declaration

public static void zip(File directory, File zipFile) 

Method Source Code


//package com.java2s;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;

import java.util.zip.ZipEntry;

import java.util.zip.ZipOutputStream;

public class Main {
    /**// w w w. j a v  a2s  .  co  m
     * Zip.
     *
     * @param directory the directory
     * @param zipFile the zip file
     */
    public static void zip(File directory, File zipFile) {
        try {
            FileOutputStream os = new FileOutputStream(zipFile);
            ZipOutputStream zos = new ZipOutputStream(os);
            zipDirectory(directory, directory, zos);
            zos.close();
            os.close();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * Zip directory.
     *
     * @param root the root
     * @param directory the directory
     * @param zos the zos
     * @throws Exception the exception
     */
    static void zipDirectory(File root, File directory, ZipOutputStream zos) throws Exception {
        for (File item : directory.listFiles()) {
            if (item.isDirectory()) {
                zipDirectory(root, item, zos);
            } else {
                byte[] readBuffer = new byte[2156];
                int bytesIn;
                FileInputStream fis = new FileInputStream(item);
                String path = item.getAbsolutePath().substring(root.getAbsolutePath().length() + 1);
                ZipEntry anEntry = new ZipEntry(path);
                zos.putNextEntry(anEntry);
                while ((bytesIn = fis.read(readBuffer)) != -1) {
                    zos.write(readBuffer, 0, bytesIn);
                }
                fis.close();
            }
        }
    }
}

Related

  1. zip(File dir, ZipOutputStream out, String prefix)
  2. zip(File dir2zip, File zipFile)
  3. zip(File directory, File base, ZipOutputStream zos)
  4. zip(File directory, File base, ZipOutputStream zos, byte[] buffer)
  5. zip(File directory, File file)
  6. zip(File directory, File zipFile)
  7. zipDirectories(List directories, File baseDirectory, File zipFile)
  8. zipDirectory(File baseDirectory, File output)
  9. zipDirectory(File dir, boolean includeDirInZip, boolean includeHidden)