简体   繁体   中英

Unable to unzip a file using java but able to unzip it using 7zip

I am trying to unzip a file using java but the following code doesnt enter the while loop as 'ze' is null. However the same file I am able to unzip using 7zip application. Can someone let me know why is this happpening?

try{

        //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(); 
    }

The javadocs here: https://docs.oracle.com/javase/7/docs/api/java/util/zip/ZipInputStream.html says that getNextEntry() will return null if there are no more entries. Check if your zip file actually contains files in it or is it empty.

I tried your code with a zip that contained files and it ran correctly. I tried it with an empty zip file and ze was null for the empty file and so it did not enter the while loop.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM