zip Directory - Java File Path IO

Java examples for File Path IO:Zip File

Description

zip Directory

Demo Code


//package com.java2s;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;

import java.util.zip.ZipEntry;

import java.util.zip.ZipOutputStream;

public class Main {
    public static final void zipDirectory(File directory, File zip)
            throws IOException {
        ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(zip));
        zos.setLevel(9);/*from   w  w  w.j  a v  a 2 s.c om*/
        zip(directory, directory, zos);
        zos.close();
    }

    /**
     * 
     * 
     * @param directory
     * @param zip  full path to zip archive with it name
     * @throws java.io.IOException
     */
    public static final void zipDirectory(String directory, String zip)
            throws IOException {
        zipDirectory(new File(directory), new File(zip));
    }

    private static final void zip(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()) {
                zip(files[i], base, zos);
            } else {
                FileInputStream in = new FileInputStream(files[i]);
                ZipEntry entry = new ZipEntry(files[i].getPath().substring(
                        base.getPath().length() + 1));
                zos.putNextEntry(entry);
                while (-1 != (read = in.read(buffer))) {
                    zos.write(buffer, 0, read);
                }
                in.close();
            }
        }
    }
}

Related Tutorials