Java Zip Folder zipDir(File zipFile, File dirObj)

Here you can find the source of zipDir(File zipFile, File dirObj)

Description

zip Dir

License

Open Source License

Declaration

public static void zipDir(File zipFile, File dirObj) throws Exception 

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.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

public class Main {
    public static void zipDir(File zipFile, File dirObj) throws Exception {
        // File dirObj = new File(dir);
        if (!dirObj.isDirectory()) {
            System.err.println(dirObj.getName() + " is not a directory");
            System.exit(1);//from  w  ww. j av a 2s .  c  o m
        }

        try {

            ZipOutputStream out = new ZipOutputStream(new FileOutputStream(zipFile));

            System.out.println("Creating : " + zipFile);

            addDir(dirObj, out);
            // Complete the ZIP file
            out.close();

        } catch (IOException e) {
            throw new Exception(e.getMessage());
        }

    }

    private static void addDir(File dirObj, ZipOutputStream out) throws IOException {
        File[] dirList = dirObj.listFiles();
        byte[] tmpBuf = new byte[1024];

        for (int i = 0; i < dirList.length; i++) {
            if (dirList[i].isDirectory()) {
                addDir(dirList[i], out);
                continue;
            }

            FileInputStream in = new FileInputStream(dirList[i].getAbsolutePath());
            System.out.println(" Adding: " + dirList[i].getAbsolutePath());

            out.putNextEntry(new ZipEntry(dirList[i].getAbsolutePath()));

            // Transfer from the file to the ZIP file
            int len;
            while ((len = in.read(tmpBuf)) > 0) {
                out.write(tmpBuf, 0, len);
            }

            // Complete the entry
            out.closeEntry();
            in.close();
        }
    }
}

Related

  1. zipDir(File zipDir, ZipOutputStream zos, boolean recurse)
  2. zipDir(File zipDir, ZipOutputStream zos, String archiveSourceDir)
  3. zipDir(File zipDir, ZipOutputStream zos, String basePath)
  4. zipDir(File zipDir, ZipOutputStream zos, String name)
  5. zipDir(File zipFile, File dir, boolean includeRoot)
  6. zipDir(final String dir2zip, final ZipOutputStream zos, final String root)
  7. zipDir(String baseDir, String dir2zip, ZipOutputStream zos)
  8. zipDir(String dir, ZipOutputStream zos)
  9. zipDir(String dir2zip, FilenameFilter filter, java.util.zip.ZipOutputStream zos, int bufferSize)