创建仅在内存中使用的gzip压缩文件

3
我希望您能在不必先将文件写入磁盘的情况下,使用ruby压缩文件。目前我只知道通过使用Zlib::GzipWriter来实现,但是我真的希望可以避免这个步骤,仅在内存中完成操作。
我尝试了以下方法,但未成功:
def self.make_gzip(data)
  gz = Zlib::GzipWriter.new(StringIO.new)
  gz << data
  string = gz.close.string
  StringIO.new(string, 'rb').read
end

以下是我测试的结果:
# Files
normal = File.new('chunk0.nbt')
gzipped = File.new('chunk0.nbt.gz')


# Try to create gzip in program
make_gzip normal
=> "\u001F\x8B\b\u0000\x8AJhS\u0000\u0003S\xB6q\xCB\xCCI\xB52\xA8000OK1L\xB2441J5\xB5\xB0\u0003\u0000\u0000\xB9\x91\xDD\u0018\u0000\u0000\u0000"

# Read from a gzip created with the gzip command
reader = Zlib::GzipReader.open gzipped
reader.read
"\u001F\x8B\b\u0000\u0000\u0000\u0000\u0000\u0000\u0000\xED]\xDBn\xDC\xC8\u0011%\x97N\xB82<\x9E\x89\xFF!\xFF!\xC9\xD6dFp\x80\u0005\xB2y\r\"\xEC\n\x89\xB0\xC6\xDAX+A./\xF94\xBF\u0006\xF1\x83>`\u0005\xCC\u000F\xC4\xF0\u000F.............(for 10,000 columns)

对我来说运行良好。你所说的“没有成功”是什么意思?顺便说一下,最后一行是多余的。你可以直接返回gz.close.string - Arie Xiao
好的,它返回了数据,但是不正确。这是我在程序中创建gzip时的一些输出,以及当我从真正的gzip中读取时的输出:http://pastebin.com/RBNvx6r4 - August
这里网站被屏蔽了,你最好直接更新你的帖子。这样可以帮助其他人知道你的问题是什么。 - Arie Xiao
好的,帖子已经更新。 - August
1个回答

3
你实际上正在对以下代码进行gzip压缩:normal.to_s(类似于"#<File:0x007f53c9b55b48>")。

# Files
normal = File.new('chunk0.nbt')

# Try to create gzip in program
make_gzip normal

您需要阅读文件内容,并对内容进行make_gzip操作:

make_gzip normal.read

正如我所评论的,make_gzip 可以更新:

def self.make_gzip(data)
  gz = Zlib::GzipWriter.new(StringIO.new)
  gz << data
  gz.close.string
end

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接