【问题标题】:Create in-memory only gzip仅在内存中创建 gzip
【发布时间】:2014-05-06 01:45:13
【问题描述】:

我正在尝试用 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
  • 嗯,它返回数据,但它不正确。这是我在程序中创建 gzip 以及从真正的 gzip 读取时的一些输出:pastebin.com/RBNvx6r4
  • 网站在这里被屏蔽了,你最好直接更新你的帖子。它可以帮助其他人了解您的问题。
  • 好的,帖子已更新。

标签: ruby gzip zlib


【解决方案1】:

您实际上是在以下代码中压缩normal.to_s(类似于"#&lt;File:0x007f53c9b55b48&gt;")。

# 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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-01-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多