Compress the given root and all its underlying folders and files to the target file, preserving files hierarchy. - Java File Path IO

Java examples for File Path IO:Directory Content

Description

Compress the given root and all its underlying folders and files to the target file, preserving files hierarchy.

Demo Code


import java.io.*;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;
import java.util.jar.JarEntry;
import java.util.jar.JarFile;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
import java.util.zip.ZipOutputStream;
import javax.swing.filechooser.FileFilter;

public class Main{
    private static final FileFilter ZIP_FILE_FILTER = new FileFilter() {

        @Override/*from   ww w.j av a 2 s .  c  o  m*/
        public boolean accept(File pathname) {
            return pathname.getName().endsWith(ZIP_FILE_EXTENSION);
        }

        @Override
        public String getDescription() {
            // TODO Auto-generated method stub
            return null;
        }
    };
    /**
     * Compress the given root and all its underlying folders and files to the
     * target file, preserving files hierarchy.
     * 
     * @param root
     *            The root of the Zip archive
     * @param target
     *            The target archive file (must be a valid Zip file name)
     * @throws IOException
     *             If an error occurs during the process
     */
    public static void zipDirectory(final File root, final File target)
            throws IOException {
        if (!ZIP_FILE_FILTER.accept(target)) {
            throw new IllegalArgumentException("Target file "
                    + target.getName() + " is not a valid Zip file name");
        }

        byte[] buffer = new byte[1024];
        FileOutputStream fileOutputStream = null;
        ZipOutputStream zipOutputStream = null;

        try {
            fileOutputStream = new FileOutputStream(target);
            zipOutputStream = new ZipOutputStream(fileOutputStream);

            FileInputStream fileInputStream = null;

            for (File file : ZipUtils.listFilesRecursive(root)) {
                ZipEntry entry = new ZipEntry(ZipUtils.stripRootInclusive(
                        file, root).getPath());
                zipOutputStream.putNextEntry(entry);
                try {
                    fileInputStream = new FileInputStream(file);
                    int length;
                    while ((length = fileInputStream.read(buffer)) > 0) {
                        zipOutputStream.write(buffer, 0, length);
                    }
                } finally {
                    fileInputStream.close();
                }

                zipOutputStream.closeEntry();
            }
        } finally {
            zipOutputStream.close();
        }
    }
    /**
     * List all files and folders from the given root.
     * 
     * @param root
     *            The root of the listing
     * @return A list of the files under the given root
     */
    public static List<File> listFilesRecursive(final File root) {
        List<File> packedFiles = new ArrayList<File>();

        File[] subFiles = root.listFiles();
        if (subFiles == null) {
            return packedFiles;
        }

        for (File file : subFiles) {
            if (file.isFile()) {
                File packedFile = new File(root, file.getName());
                packedFiles.add(packedFile);
            } else if (file.isDirectory()) {
                packedFiles.addAll(ZipUtils.listFilesRecursive(file));
            }
        }

        return packedFiles;
    }
    /**
     * Strip the given file from any parent path, preserving the root as the
     * absolute parent.
     * <p>
     * Ex. with 'Folder' as the root: /home/johnj/Test/Folder/File.txt =>
     * /Folder/File.txt
     * </p>
     * 
     * @param file
     *            The file to strip
     * @param root
     *            The root of the stripping
     * @return The stripped file
     */
    private static File stripRootInclusive(final File file, final File root) {
        String parentPath = root.getParent();

        if (parentPath == null) {
            // Assuming no existing parent.
            return file;
        }

        return new File(file.getAbsolutePath().substring(
                parentPath.length()));
    }
}

Related Tutorials