Java Zip Directory zipDirectory(File directory, File zip)

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

Description

zip Directory

License

Apache License

Declaration

public static final void zipDirectory(File directory, File zip) throws IOException 

Method Source Code

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

import java.io.File;

import java.io.FileOutputStream;
import java.io.IOException;

import java.io.RandomAccessFile;

import java.util.zip.ZipEntry;

import java.util.zip.ZipOutputStream;

public class Main {
    public static final void zipDirectory(File directory, File zip) throws IOException {
        FileOutputStream fos = new FileOutputStream(zip);
        ZipOutputStream zos = new ZipOutputStream(fos);
        zipArchive(directory, directory, zos);
        zos.close();//from w w  w  .  j  a v  a2  s .co m
        fos.close();
    }

    private static final void zipArchive(File directory, File base, ZipOutputStream zos) throws IOException {
        File[] files = directory.listFiles();
        byte[] buffer = new byte[8192];
        int read = 0;
        for (int i = 0, n = files.length; i < n; i++) {
            if (files[i].isDirectory()) {
                zipArchive(files[i], base, zos);
            } else {
                //FileInputStream in = new FileInputStream(files[i]);
                RandomAccessFile raf = new RandomAccessFile(files[i], "r");
                ZipEntry entry = new ZipEntry(
                        files[i].getPath().substring(base.getPath().length() + 1).replace("\\", "/"));
                zos.putNextEntry(entry);
                try {
                    while (-1 != (read = raf.read(buffer))) {
                        zos.write(buffer, 0, read);
                    }
                } finally {
                    raf.close();
                }
            }
        }
    }
}

Related

  1. zipDirectory(File dir, boolean includeDirInZip, boolean includeHidden)
  2. zipDirectory(File dir, File zipFile)
  3. zipDirectory(File dir, String base, ZipOutputStream zout)
  4. zipDirectory(File dir, String zipDirName)
  5. zipDirectory(File directory, File zip)
  6. zipDirectory(File directory, File zipFile)
  7. zipDirectory(File directory, File zipFile)
  8. zipDirectory(File directory, File zipFile, Pattern exclusion)
  9. zipDirectory(File directory, ZipOutputStream zipout, final FilenameFilter filter)