使用 java.util.zip.ZipOutputStream 时 zip 文件中的目录 [英] directories in a zip file when using java.util.zip.ZipOutputStream
问题描述
假设我有一个文件 t.txt、一个目录 t 和另一个文件 t/t2.txt.如果我使用 linux zip 实用程序zip -r t.zip t.txt t",我会得到一个包含以下条目的 zip 文件(unzip -l t.zip):
Lets say I have a file t.txt, a directory t and another file t/t2.txt. If I use the linux zip utility "zip -r t.zip t.txt t", I get a zip file with the following entries in them (unzip -l t.zip):
Archive: t.zip
Length Date Time Name
-------- ---- ---- ----
9 04-11-09 09:11 t.txt
0 04-11-09 09:12 t/
15 04-11-09 09:12 t/t2.txt
-------- -------
24 3 files
如果我尝试使用 java.util.zip.ZipOutputStream 复制该行为并为该目录创建一个 zip 条目,java 将引发异常.它只能处理文件.我可以在 zip 文件中创建一个 t/t2.txt 条目并将使用 t2.txt 文件内容添加到其中,但我无法创建目录.这是为什么?
If I try to replicate that behavior with java.util.zip.ZipOutputStream and create a zip entry for the directory, java throws an exception. It can handle only files. I can create a t/t2.txt entry in the zip file and add use the t2.txt file contents to it but I can't create the directory. Why is that?
推荐答案
ZipOutputStream
can 通过添加正斜杠 /
处理空目录在文件夹名称之后.试试(来自)
ZipOutputStream
can handle empty directories by adding a forward-slash /
after the folder name. Try (from)
public class Test {
public static void main(String[] args) {
try {
FileOutputStream f = new FileOutputStream("test.zip");
ZipOutputStream zip = new ZipOutputStream(new BufferedOutputStream(f));
zip.putNextEntry(new ZipEntry("xml/"));
zip.putNextEntry(new ZipEntry("xml/xml"));
zip.close();
} catch(Exception e) {
System.out.println(e.getMessage());
}
}
}
这篇关于使用 java.util.zip.ZipOutputStream 时 zip 文件中的目录的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!