在Ruby中读取未压缩的GZIP文件大小,而不需要解压

89 阅读1分钟

有些情况下,你有一个压缩的GZIP文件,你想确定未压缩的数据大小,而不需要提取它。

例如,如果你处理大型的基于文本的文件,你可以直接在浏览器中显示其内容,或者根据文件的大小,应要求将其作为一个文件共享。

对我们来说,幸运的是,GZIP文件格式规范包括以下声明。

         +=======================+
         |...compressed blocks...| (more-->)
         +=======================+

           0   1   2   3   4   5   6   7
         +---+---+---+---+---+---+---+---+
         |     CRC32     |     ISIZE     |
         +---+---+---+---+---+---+---+---+

         ISIZE (Input SIZE)
            This contains the size of the original (uncompressed) input
            data modulo 2^32.

这意味着,只要未压缩的有效载荷小于4GB,ISIZE值将代表未压缩的数据大小。

你可以在Ruby中通过组合#seek#read#unpack1 ,如下所示得到它。

# Open file for reading
file = File.open('data.gzip')
# Move to the end to obtain only the ISIZE data
file.seek(-4, 2)
# Read the needed data and decode it to unsigned int
size = file.read(4).unpack1('I')
# Close the file after reading
file.close
# Print the result
puts "Your uncompressed data size: #{size} bytes"