【问题标题】:Unable to unzip a file using java but able to unzip it using 7zip无法使用 java 解压缩文件,但能够使用 7zip 解压缩文件
【发布时间】:2016-07-29 02:43:56
【问题描述】:

我正在尝试使用 java 解压缩文件,但以下代码没有进入 while 循环,因为 'ze' 为空。但是,我可以使用 7zip 应用程序解压缩同一个文件。有人可以告诉我为什么会这样吗?

试试{

        //get the zip file content
        ZipInputStream zis = 
            new ZipInputStream(new FileInputStream(zipFile));
        //get the zipped file list entry
        ZipEntry ze = zis.getNextEntry();

        while(ze!=null){

           String fileName = ze.getName();
           File newFile = new File(outputFolder + File.separator + fileName);

           System.out.println("file unzip : "+ newFile.getAbsoluteFile());

            //create all non exists folders
            //else you will hit FileNotFoundException for compressed folder
            new File(newFile.getParent()).mkdirs();

            FileOutputStream fos = new FileOutputStream(newFile);             

            int len;
            while ((len = zis.read(buffer)) > 0) {
            fos.write(buffer, 0, len);
            }

            fos.close();   
            ze = zis.getNextEntry();
        }

        zis.closeEntry();
        zis.close();

        System.out.println("Done");

    }catch(IOException ex){
       ex.printStackTrace(); 
    }

【问题讨论】:

  • 是 .7z 文件还是 .zip 文件?

标签: java zip unzip 7zip zipinputstream


【解决方案1】:

这里的 javadocs:https://docs.oracle.com/javase/7/docs/api/java/util/zip/ZipInputStream.html 说如果没有更多条目,getNextEntry() 将返回 null。 检查您的 zip 文件中是否实际包含文件或是否为空。

我使用包含文件的 zip 尝试了您的代码,并且它运行正常。我用一个空的 zip 文件试了一下,空文件的 ze 为空,所以它没有进入 while 循环。

【讨论】:

  • 我整理出来了。问题是我的文件被压缩而不是压缩。我使用了 GZIPInputStream 并且运行良好 :)
  • 感谢@posiedon 的帮助
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-09-01
  • 2022-07-27
  • 1970-01-01
相关资源
最近更新 更多