【问题标题】:FileNotFoundException when trying to unzip an archive with java.util.zip.ZipFile尝试使用 java.util.zip.ZipFile 解压缩档案时出现 FileNotFoundException
【发布时间】:2011-11-04 05:30:12
【问题描述】:

我有一个我无法弄清楚的愚蠢问题。谁能帮我? 我的代码如下:

String zipname = "C:/1100.zip";
    String output = "C:/1100";
    BufferedInputStream bis = null;
    BufferedOutputStream bos = null;
    try {
        ZipFile zipFile = new ZipFile(zipname);
        Enumeration<?> enumeration = zipFile.entries();
        while (enumeration.hasMoreElements()) {
            ZipEntry zipEntry = (ZipEntry) enumeration.nextElement();
            System.out.println("Unzipping: " + zipEntry.getName());
            bis = new BufferedInputStream(zipFile.getInputStream(zipEntry));
            int size;
            byte[] buffer = new byte[2048];

它不会创建文件夹,但调试会显示所有正在生成的内容。 为了创建一个文件夹,我使用了代码

if(!output.exists()){ output.mkdir();} // here i get an error saying filenotfoundexception

            bos = new BufferedOutputStream(new FileOutputStream(new File(outPut)));
            while ((size = bis.read(buffer)) != -1) {
                bos.write(buffer, 0, size);
            }
        }
    } catch (Exception ex) {
        ex.printStackTrace();
    } finally {
        bos.flush();
        bos.close();
        bis.close();
    }

我的 zip 文件包含图像:a.jpg b.jpg... 在同一层次结构中,我有 abc.xml。 我需要按原样提取 zip 文件中的内容。 这里有任何帮助。

【问题讨论】:

    标签: java unzip filenotfoundexception


    【解决方案1】:

    您的代码存在一些问题:outPut 在哪里声明? output 不是文件而是字符串,所以exists() 和mkdir() 不存在。首先声明output,例如:

    File output = new File("C:/1100");
    

    此外,outPut(带有大 P)未声明。类似于output + File.seprator + zipEntry.getName()。

     bos = new BufferedOutputStream(new FileOutputStream(output + File.seprator + zipEntry.getName()));
    

    请注意,您不需要将 File 传递给 FileOutputStream,如 the documentation 中所示的构造函数。

    此时,如果您的 Zip 文件不包含目录,您的代码应该可以工作。但是,当打开输出流时,如果 zipEntry.getName() 有目录组件(例如somedir/filename.txt),打开流将导致FileNotFoundException,因为您尝试创建的文件的父目录没有存在。如果您希望能够处理此类 zip 文件,您将在以下位置找到答案:How to unzip files recursively in Java?

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-04-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-09-07
    • 1970-01-01
    • 1970-01-01
    • 2019-09-09
    相关资源
    最近更新 更多