Adil Hussain
Adil Hussain

Reputation: 32103

Possible to determine size of file to be unzipped?

I currently have the following code which uses a ZipInputStream instance to decompress a zip file to a target location on the phone:

ZipInputStream zipInputStream = new ZipInputStream(new FileInputStream(sourceZipFile));
ZipEntry zipEntry = null;

while ((zipEntry = zipInputStream.getNextEntry()) != null) {
  File zipEntryFile = new File(targetFolder, zipEntry.getName());
  // write contents of 'zipEntry' to 'zipEntryFile'
}

Does anyone know whether it is possible (using the setup above or otherwise) to get (an estimate of) the total number of files or bytes to be unzipped before commencing so that I can display a progress indicator as the decompression proceeds? I thought ZipInputStream might have a getTotalEntries() or similar method but I can't find anything like this.

Upvotes: 2

Views: 7325

Answers (3)

Alexey Sviridov
Alexey Sviridov

Reputation: 3490

Kotlin solution:

val uncompressedSize = ZipFile(fileName).use { zipFile -> 
  zipFile.entries().asSequence().sumOf { zipEntry -> zipEntry.size } 
}

Upvotes: 1

npe
npe

Reputation: 15699

Use the ZipEntry#getSize() method. It returns the size of uncompressed file.

If you have more than one entry (file) inside ZIP file, just iterate through them first (without extracting them), and add together all file sizes. This might be a pretty good estimate.

Note, that if you need to know the exact number of bytes those files will occupy on disk, you will also need to know the exact size of a cluster in your filesystem.

Upvotes: 4

trumpetlicks
trumpetlicks

Reputation: 7065

As npe stated, ZipEntry will get the uncompressed size of the file from within the zip file.

I think what you'll need to do is perform one pass using

getNextEntry

until done, counting the entries along the way (size and amount of entries), then restart the actual decompression afterwards

Upvotes: 1

Related Questions