使用java.util.zip.ZipOutputStream时zip文件中的目录 [英] directories in a zip file when using java.util.zip.ZipOutputStream

查看:477
本文介绍了使用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):

 存档:t.zip 
长度日期时间名称
-------- ---- ---- --- -
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个文件

如果我尝试使用java.util.zip.ZipOutputStream复制该行为,并为目录创建一个zip条目,则java会抛出异常。它只能处理文件。我可以在zip文件中创建一个t / t2.txt条目,并添加t2.txt文件内容,但是我无法创建目录。为什么是这样?

解决方案

看起来ZipOutputStream不能处理空目录,但你有一个文件,所以它不空。尝试( from

  public class Test {
public static void main(String [] args){
try {
FileOutputStream f = new FileOutputStream(test 。压缩);
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());
}
}
}


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?

解决方案

It looks like ZipOutputStream can't handle empty directories, but you have a file in there so its not empty. 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆