Find the size of the file inside a GZIP file

前端 未结 4 907
长情又很酷
长情又很酷 2020-12-06 02:58

Is there a way to find out the size of the original file which is inside a GZIP file in java?

As in, I have a file a.txt of 15 MB which has been GZipped to a.gz of s

4条回答
  •  伪装坚强ぢ
    2020-12-06 03:46

    Below is one approach for this problem - certainly not the best approach, however since Java doesn't provide an API method for this (unlike that when dealing with Zip files), it's the only way I could think of, apart from one of the comments above, which talked about reading in the last 4 bytes (assuming the file is under 2Gb in size).

    GZIPInputStream zis = new GZIPInputStream(new FileInputStream(new File("myFile.gz")));
    long size = 0;
    
    while (zis.available() > 0)
    {
      byte[] buf = new byte[1024];
      int read = zis.read(buf);
      if (read > 0) size += read;
    }
    
    System.out.println("File Size: " + size + "bytes");
    zis.close();
    

    As you can see, the gzip file is read in, and the number of bytes read in is totalled indicating the uncompressed file size.

    While this method does work, I really cannot recommend using it for very large files, as this may take several seconds. (unless time is not really too much of a constraint)

提交回复
热议问题