使用 java.util.zip.ZipOutputStream 时 zip 文件中的目录
假设我有一个文件 t.txt、一个目录 t 和另一个文件 t/t2.txt。 如果我使用 Linux zip 实用程序“zip -r t.zip t.txt t”,我会得到一个包含以下条目的 zip 文件(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
: util.zip.ZipOutputStream 并为目录创建 zip 条目,java 抛出异常。 它只能处理文件。 我可以在 zip 文件中创建 at/t2.txt 条目并向其中添加使用 t2.txt 文件内容,但无法创建该目录。 这是为什么?
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
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
ZipOutputStream
可以通过在文件夹名称后添加正斜杠/
来处理空目录。 尝试(来自)ZipOutputStream
can handle empty directories by adding a forward-slash/
after the folder name. Try (from)只需查看 java.util.zip.ZipEntry 的源代码即可。 如果 ZipEntry 的名称以“/”字符结尾,则它将其视为目录。 只需在目录名称后加上“/”即可。
检查此示例以仅压缩空目录,
http://bethecoder.com/applications/tutorials/showTutorials.action?tutorialId=Java_ZipUtilities_ZipEmptyDirectory祝
你好运。
Just go through the source of java.util.zip.ZipEntry. It treats a ZipEntry as directory if its name ends with "/" characters. Just suffix the directory name with "/".
Check this example for zipping just the empty directories,
http://bethecoder.com/applications/tutorials/showTutorials.action?tutorialId=Java_ZipUtilities_ZipEmptyDirectory
Good luck.
就像其他人所说的那样,要添加空目录,请在目录名称中添加“/”。
注意不要添加 File.separator (等于“\”),这实际上会向 zip 中添加一个空文件。
我花了一段时间才明白我的错误是什么 - 希望我可以节省其他一些时间......
Like others said here to add empty directory add "/" to the directory name.
Pay attention NOT to add File.separator (equals to "\") which actually add an empty file to the zip.
It took me a while to understand what was my mistake - hope I save other some time...
Java 程序到 Zip(文件夹包含空或完整文件夹)
Java Program to Zip(folders contains either empty or full ones)
您可以在文件夹名称末尾添加“/”。 只需使用以下命令:
You can add "/" at the end of folder name. Just use the following command:
String dir = "E:\Infor\Marketing\JobLog\Cloud_MomBuild_NoMirror";
String dir = "E:\Infor\Marketing\JobLog\Cloud_MomBuild_NoMirror";