递归地压缩包含Java中任意数量的文件和子目录的目录?

时间:2010-03-08 18:50:18

标签: java file directory zip

是否有一种简单的方法可以递归地压缩一个目录,该目录可能包含也可能不包含任意数量的文件和任意数量级别的子目录?

3 个答案:

答案 0 :(得分:10)

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();
            }
        }
    }
}

答案 1 :(得分:1)

答案 2 :(得分:-2)

我在ruby中使用ZipFileSystem实现非常成功,尽管我从未在java中使用它。您可能需要检查this