Search code examples
androidzipunzip

Unzip a Byte zip data


I want to unzip a zip file. I have the zip data as bytes. I used the below code to unzip the zip file. But I can read the names from files in the zip file. But the output data is corrupted. I think I am reading the whole data in ZipInputStream. The how can i read each file data? Plz help me Thanks..

ByteArrayInputStream binput = new ByteArrayInputStream(zipeddatainbyte);
    ZipInputStream mzipstream = new ZipInputStream(binput);
    File f2 = new File("/sdcard/Unziped Data/");
    f2.mkdirs();
    ZipEntry entry;
    FileOutputStream out;
    byte[] bout=null;
    try {
        while ((entry = mzipstream.getNextEntry()) != null) {
            System.out.println("entry: " + entry.getName() + ", "
                    + entry.getSize());
            bout=new byte[(int) entry.getSize()];
            mzipstream.read(bout);
            out = new FileOutputStream("/sdcard/Unziped Data/"+entry.getName());
            out.write(bout);
            out.close();



        }
    } catch (IOException e) {

        e.printStackTrace();
    }

Solution

  • You should not trust entry.getSize(), but try to read till the end of the stream for each ZipEntry and control what is actually read. This applies not only to ZipInputStreams but also to any Java InputStream. This snippet is extracted from here:

    ZipEntry entrada;
    while (null != (entrada=zis.getNextEntry()) ){
       System.out.println(entrada.getName());
    
       FileOutputStream fos = new FileOutputStream(entrada.getName());
       int leido;
       byte [] buffer = new byte[1024];
       while (0<(leido=zis.read(buffer))){
          fos.write(buffer,0,leido);
       }
       fos.close();
       zis.closeEntry();
    }