以递归方式压缩包含任意数量的Java文件和子目录的目录?

以递归方式压缩包含任意数量的Java文件和子目录的目录?

问题描述:

是否有递归压缩ZIP目录的简单方法,该目录可能包含或不包含任何数量的文件和任意数目的子目录级别?以递归方式压缩包含任意数量的Java文件和子目录的目录?

+1

我检查阿帕奇百科全书压缩,和它的不存在。奇; “使一个zip文件不在这个目录中”似乎很常见的功能。 – 2010-03-08 18:54:37

+0

仅供参考:您可以在DotNetZip中使用'ZipFile.AddDirectory();' – Cheeso 2010-03-08 22:36:36

我在ruby中使用ZipFileSystem实现取得了巨大成功,尽管我从未在java中使用它。你可能想看看this出:

+0

答案中的链接已死(404未找到)。 – Pang 2016-01-13 03:16:08

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

适用于我,但由于某种神秘原因,还会将“[email protected]”这样的文件添加到存档中。任何想法我做错了什么? – 2017-10-02 11:29:46