在Java中递归压缩包含任意数量文件和子目录的目录?
有没有一种简单的方法可以递归地压缩一个可能包含或不包含任意数量的文件和任意级别的子目录?我在ruby中使用ZipFileSystem实现非常成功,尽管我从未在java中使用过它。您可能想签出:您可以使用在Java中递归压缩包含任意数量文件和子目录的目录?,java,file,directory,zip,Java,File,Directory,Zip,有没有一种简单的方法可以递归地压缩一个可能包含或不包含任意数量的文件和任意级别的子目录?我在ruby中使用ZipFileSystem实现非常成功,尽管我从未在java中使用过它。您可能想签出:您可以使用 而且。我检查了Apache Commons Compress,但它不在那里。古怪的“从该目录生成一个zip文件”似乎是一个非常常见的功能。仅供参考:您可以在DotNetZip中使用ZipFile.AddDirectory()答案中的链接已失效(404未找到)。对我来说效果很好,但出于某种神秘的原
而且。我检查了Apache Commons Compress,但它不在那里。古怪的“从该目录生成一个zip文件”似乎是一个非常常见的功能。仅供参考:您可以在DotNetZip中使用
ZipFile.AddDirectory()代码>答案中的链接已失效(404未找到)。对我来说效果很好,但出于某种神秘的原因,还添加了类似“java.io”的文件。FileInputStream@1c636e41“到档案馆去。知道我做错了什么吗?
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();
}
}
}
}