Getting the size of ZipInputStream
Asked Answered
F

3

7

Is there anyway to find/estimate the size of ZipInputStream before we completely read the stream?

For instance, we can get the entry's metadata with getNextEntry before we can read the userdata.

Inputstream has a method available() to return an estimate of the number of bytes that can be read from this input stream but I am not able to find a similar method for ZipInputStream.

Flier answered 19/6, 2012 at 9:35 Comment(2)
Do you have access to the ZipFile where the stream came from?Judicious
Nope. We just have a stream coming in. I wanted to know if there was someway to get the metadata before reading the complete stream.Flier
C
3

ZipInputStream has method available() but it returns 0 or 1.

To get the estimated size of any type of file, you can use FileInputStream and then to read zip file use ZipInputStream. Ex.

 public class ZipUtil {

    public static void main(String[] args) throws Exception {
        ZipInputStream zis = null;

        FileInputStream fis = new FileInputStream("C:/catalina.zip");
        int size = fis.available();
        System.out.println("size in KB : " + size/1024);
        zis = new ZipInputStream(fis);        

        ZipEntry ze;
        while ((ze = zis.getNextEntry()) != null) {
            System.out.println(ze.getName());
        }
    }
}
Cloven answered 19/6, 2012 at 9:46 Comment(2)
The problem with this approach is that I dont have a zip file that I can make into a FileInputStream. I only have a ZipInputStream to work with.Flier
There is a specific warning in the Javadoc against using available() as a total size value.Shaunda
J
3

If you have just the stream, then I don't think so.

The zip file format has just a sequence of entries, and then a global directory (which has a table of all files and their sizes) at the end. So without access to the file, you won't get to that information.

Judicious answered 19/6, 2012 at 9:47 Comment(0)
S
1

Inputstream has a method available() to return an estimate of the number of bytes that can be read from this input stream

without blocking. Not the same thing. There is a specific warning in the Javadoc about not treating this value as a total file size.

but I am not able to find a similar method for ZipInputStream.

That's strange because it's there. However it returns zero, which is the best estimate it can make of how much can be read without blocking.

Why? Because (a) it's a stream, and (ii) it's a zipped stream. There is no way of knowing how much there is without reading it all; and there is no way of knowing how much of that can be read without blocking,

Shaunda answered 19/6, 2012 at 10:29 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.