Recursively ZIP a directory containing any number of files and subdirectories in Java?

允我心安 提交于 2020-01-23 01:57:44

问题


Is there an easy way to recursively ZIP a directory that may or may not contain any number of files and any number of levels of subdirectories?


回答1:


You can use: http://java.sun.com/j2se/1.4.2/docs/api/ and: http://www.java-forums.org/new-java/4123-how-do-you-recursively-traverse-through-file-folders.html




回答2:


public final class ZipFileUtil {
    public static void zipDirectory(File dir, File zipFile) throws IOException {
        FileOutputStream fout = new FileOutputStream(zipFile);
        ZipOutputStream zout = new ZipOutputStream(fout);
        zipSubDirectory("", dir, zout);
        zout.close();
    }

    private static void zipSubDirectory(String basePath, File dir, ZipOutputStream zout) throws IOException {
        byte[] buffer = new byte[4096];
        File[] files = dir.listFiles();
        for (File file : files) {
            if (file.isDirectory()) {
                String path = basePath + file.getName() + "/";
                zout.putNextEntry(new ZipEntry(path));
                zipSubDirectory(path, file, zout);
                zout.closeEntry();
            } else {
                FileInputStream fin = new FileInputStream(file);
                zout.putNextEntry(new ZipEntry(basePath + file.getName()));
                int length;
                while ((length = fin.read(buffer)) > 0) {
                    zout.write(buffer, 0, length);
                }
                zout.closeEntry();
                fin.close();
            }
        }
    }
}



回答3:


I use the ZipFileSystem implementation in ruby with great success, though I've never used it in java. You might want to check this out:



来源:https://stackoverflow.com/questions/2403830/recursively-zip-a-directory-containing-any-number-of-files-and-subdirectories-in

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!