Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Gets the uncompressed size of this GZIPInputStream?

I have a GZIPInputStream that I constructed from another ByteArrayInputStream. I want to know the original (uncompressed) length for the gzip data. Although I can read to the end of the GZIPInputStream, then count the number, it will cost much time and waste CPU. I would like to know the size before read it.

Is there a similiar method like ZipEntry.getSize() for GZIPInputStream:

public long getSize ()
Since: API Level 1
Gets the uncompressed size of this ZipEntry.

like image 886
David Guo Avatar asked Sep 06 '11 08:09

David Guo


People also ask

How do I check the size of a gzip file?

For each file, compute the ratio in sizes between gzip -c "$f" | wc -c and wc -c "$f" The average of those ratios is an approximation of the compression you should expect for a similar JS file.

How do I use GZIPInputStream?

To use the Java GZIPInputStream you must first create a GZIPInputStream instance. Here is an example of creating a GZIPInputStream instance: InputStream fileInputStream = new FileInputStream("myfile. zip"); GZIPInputStream gzipInputStream = new GZIPInputStream(fileInputStream);

What is gzip input stream?

GZIPInputStream(InputStream in) Creates a new input stream with a default buffer size. GZIPInputStream(InputStream in, int size) Creates a new input stream with the specified buffer size.


1 Answers

A more compact version of the calculation based on the 4 tail bytes (avoids using a byte buffer, calls Integer.reverseBytes to reverse the byte order of read bytes).

private static long getUncompressedSize(Path inputPath) throws IOException
{
    long size = -1;
    try (RandomAccessFile fp = new RandomAccessFile(inputPath.toFile(), "r")) {        
        fp.seek(fp.length() - Integer.BYTES);
        int n = fp.readInt();
        size = Integer.toUnsignedLong(Integer.reverseBytes(n));
    }
    return size;
}
like image 143
Michail Alexakis Avatar answered Nov 15 '22 20:11

Michail Alexakis