以递归方式压缩包含任意数量的Java文件和子目录的目录?
答
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
我检查阿帕奇百科全书压缩,和它的不存在。奇; “使一个zip文件不在这个目录中”似乎很常见的功能。 – 2010-03-08 18:54:37
仅供参考:您可以在DotNetZip中使用'ZipFile.AddDirectory();' – Cheeso 2010-03-08 22:36:36