Pradeep Vairamani
Pradeep Vairamani

Reputation: 4302

Getting the size of ZipInputStream

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.

Upvotes: 7

Views: 9697

Answers (3)

user207421
user207421

Reputation: 310874

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,

Upvotes: 1

Thilo
Thilo

Reputation: 262484

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.

Upvotes: 3

Rahul Agrawal
Rahul Agrawal

Reputation: 8971

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

Upvotes: 3

Related Questions