Search code examples
javazipinputstream

The ZipInputStream can't read all information of zip file


I wrote some code using ZipInputStream but there is something wrong with it.

ZipInputStream zin=null;
zin=new ZipInputStream(new BufferedInputStream(
    new FileInputStream("e:/testzip.zip")));
ZipEntry ze;
while((ze=zin.getNextEntry())!=null) {

     System.out.println("readfile"+ze.getName());

     int c=0;

     while((c=zin.read())>0) {
       System.out.write(c);
     }
 }
 zin.close();

There are 3 text files in the testzip.zip. That is, the right output should be the three file names and their contents. However, my output are 3 file names and 2 of their contents. Why only 2 contents, rather than 3?


Solution

  • I made a zip with 3 textfiles in; the fact that they are textfiles is important for the following code to work. I read all entries and write out it's names and contents:

    import java.io.BufferedReader;
    import java.io.InputStreamReader;
    import java.util.Enumeration;
    import java.util.zip.ZipEntry;
    import java.util.zip.ZipFile;
    
    public class Main {
    
        public static void main(String[] args) throws Exception {
            ZipFile zipFile = new ZipFile("D:\\zip.zip");
            Enumeration<? extends ZipEntry> entries = zipFile.entries();
            while(entries.hasMoreElements()) {
                ZipEntry zipEntry = entries.nextElement();
                System.out.println(zipEntry.getName());
                BufferedReader bufferedeReader = new BufferedReader(new InputStreamReader(zipFile.getInputStream(zipEntry)));
                String line = bufferedeReader.readLine();
                while(line != null) {
                    System.out.println(line);
                    line = bufferedeReader.readLine();
                }
                bufferedeReader.close();
            }
            zipFile.close();
        }
    
    }