首页 > 代码库 > Java determine uncompressed size of gzipped file

Java determine uncompressed size of gzipped file

If you want to determine the uncompressed size of a gzip file from within a program, you can extract to original file size from the gzip file. This size is stored in the last 4 bytes of the file. This will only provide the correct value if the compressed file was smaller than 4 Gb.

To extract this information and convert it to something useful in your Java program.

RandomAccessFile raf = new RandomAccessFile(file, "r");
raf.seek(raf.length() - 4);
int b4 = raf.read();
int b3 = raf.read();
int b2 = raf.read();
int b1 = raf.read();
int val = (b1 << 24) | (b2 << 16) + (b3 << 8) + b4;
raf.close();

The original size of the compressed file will now be available in the val variable in bytes.

http://www.abeel.be/wiki/Java_determine_uncompressed_size_of_gzipped_file