Java Zip Directory zipDirectory(File dir, boolean includeDirInZip, boolean includeHidden)

Here you can find the source of zipDirectory(File dir, boolean includeDirInZip, boolean includeHidden)

Description

create a zip file of the contents of the folder, optionally including the folder itself.

License

Open Source License

Parameter

Parameter Description
dir the folder
includeDirInZip if true, include the target directory in the zip file

Exception

Parameter Description
IOException an exception

Return

the zip file

Declaration

public static File zipDirectory(File dir, boolean includeDirInZip, boolean includeHidden) throws IOException 

Method Source Code


//package com.java2s;
/*  MonkeyTalk - a cross-platform functional testing tool
Copyright (C) 2012 Gorilla Logic, Inc.//from w  w w.  j av a  2 s  .c  om
    
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
    
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU Affero General Public License for more details.
    
You should have received a copy of the GNU Affero General Public License
along with this program.  If not, see <http://www.gnu.org/licenses/>. */

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;

import java.io.File;
import java.io.FileInputStream;

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

import java.util.ArrayList;

import java.util.List;

import java.util.zip.ZipEntry;

import java.util.zip.ZipOutputStream;

public class Main {
    private static final String TEMP_DIR_PREFIX = "report";
    private static final int BUFFER_SIZE = 4096;

    /**
     * create a zip file of the contents of the folder, optionally including the folder itself.
     * 
     * if "includeDirInZip" is true, the specified directory - one level only - will be included in
     * the zip file, i.e. all entry paths will begin with the directory name. For example, suppose
     * the "dir" is /home/user/banana and contains two files, "apple.txt" and "orange.txt". If
     * "includeDirInZip" is false, the zip file will contain two entries, "apple.txt" and
     * "orange.txt". If "includeDirInZip" is true, the zip file will contain three entries, "banana"
     * (a directory), and "banana/apple.txt" and "banana/orange.txt".
     * 
     * @param dir
     *            the folder
     * @param includeDirInZip
     *            if true, include the target directory in the zip file
     * @return the zip file
     * @throws IOException
     */
    public static File zipDirectory(File dir, boolean includeDirInZip, boolean includeHidden) throws IOException {
        return zipDirectory(dir, includeDirInZip, includeHidden, null);
    }

    /**
     * create a zip file of the contents of the folder, optionally including the folder itself, with
     * optional filter by Extensions to include
     * 
     * if "includeDirInZip" is true, the specified directory - one level only - will be included in
     * the zip file, i.e. all entry paths will begin with the directory name. For example, suppose
     * the "dir" is /home/user/banana and contains two files, "apple.txt" and "orange.txt". If
     * "includeDirInZip" is false, the zip file will contain two entries, "apple.txt" and
     * "orange.txt". If "includeDirInZip" is true, the zip file will contain three entries, "banana"
     * (a directory), and "banana/apple.txt" and "banana/orange.txt".
     * 
     * @param dir
     *            the folder
     * @param includeDirInZip
     *            if true, include the target directory in the zip file
     * @param excludeExtensions
     *            a list of file extensions to include; if null, all files will be included
     * @return the zip file
     * @throws IOException
     */
    public static File zipDirectory(File dir, boolean includeDirInZip, boolean includeHidden,
            List<String> extFilter) throws IOException {
        if (dir == null) {
            throw new IOException("zipDirectory was passed a null directory to zip");
        }
        File outputDir = tempDir();
        String dirName = dir.getName();
        File zipFile = new File(outputDir, dirName + ".zip");
        FileOutputStream dest = new FileOutputStream(zipFile);
        ZipOutputStream out = new ZipOutputStream(new BufferedOutputStream(dest));
        BufferedInputStream origin = null;

        try {
            // out.setMethod(ZipOutputStream.DEFLATED);
            byte data[] = new byte[BUFFER_SIZE];
            // get a list of files from current directory
            List<String> files = getAllFilesInDir(true, dir, includeHidden, null);

            for (String file : files) {
                if (extFilter != null && !extFilter.contains(getExtFromFileName(file))) {
                    System.out.println("zipDirectory: " + file + " excluded by extension");
                    continue;
                }

                File ff = new File(dir, file);
                if (!ff.exists()) {
                    System.out.println("zipDirectory: " + file + " no longer exists....");
                    continue;
                }

                if (includeDirInZip) {
                    file = dir.getName() + "/" + file;
                }

                System.out.println("zipDirectory: adding " + file);

                FileInputStream fi = new FileInputStream(ff);
                ZipEntry entry = new ZipEntry(file);
                out.putNextEntry(entry);

                if (!ff.isDirectory()) {
                    try {
                        origin = new BufferedInputStream(fi, BUFFER_SIZE);
                        int count;
                        while ((count = origin.read(data, 0, BUFFER_SIZE)) != -1) {
                            out.write(data, 0, count);
                        }
                    } finally {
                        origin.close();
                    }
                }
            }
        } finally {
            if (out != null) {
                out.close();
            }
        }
        return zipFile;
    }

    /**
     * Create a child temp folder inside the main temp dir.
     * 
     * @return the folder
     * @throws IOException
     */
    public static File tempDir() throws IOException {
        final File dir = File.createTempFile(TEMP_DIR_PREFIX, Long.toString(System.nanoTime()));

        if (!dir.delete()) {
            throw new IOException("failed to delete file: " + dir.getAbsolutePath());
        }

        if (!dir.mkdir()) {
            throw new IOException("failed to create dir: " + dir.getAbsolutePath());
        }

        return dir;
    }

    private static List<String> getAllFilesInDir(boolean traverseSubDirs, File dir, boolean includeHidden,
            String prefix) {
        List<String> files = new ArrayList<String>();
        String fileNames[] = dir.list();

        for (String fileName : fileNames) {
            File currentFile = new File(dir, fileName);
            if (currentFile.isHidden() && !includeHidden) {
                continue;
            }
            if (currentFile.isDirectory()) {
                if (traverseSubDirs) {
                    String pfx;
                    if (prefix == null || prefix.length() == 0) {
                        pfx = fileName;
                    } else {
                        pfx = prefix + "/" + fileName;
                    }
                    files.addAll(getAllFilesInDir(true, currentFile, includeHidden, pfx));
                }
            } else {
                String fullname = fileName;
                if (prefix != null && prefix.length() > 0) {
                    fullname = prefix + "/" + fileName;
                }
                files.add(fullname);
            }
        }
        return files;
    }

    public static String getExtFromFileName(String name) {
        name = new File(name).getName();
        return name.substring(name.lastIndexOf(".") + 1);
    }
}

Related

  1. zip(File directory, File file)
  2. zip(File directory, File zipFile)
  3. zip(File directory, File zipFile)
  4. zipDirectories(List directories, File baseDirectory, File zipFile)
  5. zipDirectory(File baseDirectory, File output)
  6. zipDirectory(File dir, File zipFile)
  7. zipDirectory(File dir, String base, ZipOutputStream zout)
  8. zipDirectory(File dir, String zipDirName)
  9. zipDirectory(File directory, File zip)