【问题标题】:Zlib::GzipFile::Error: not in gzip formatZlib::GzipFile::Error: 不是 gzip 格式
【发布时间】:2017-02-08 19:40:49
【问题描述】:

我正在尝试使用zlibjruby 解码压缩后的字符串。这是最小的工作示例。

require 'stringio'
require 'zlib'

str = 'H4sIAAAAAAAA/y2NwQrDIBAFfyXstUbWNWrir5RSrEoQUi2JOZSQf6+EHt8wzDtgKd7VVPIG9n7AMwWwYhj1MBkkwtEwcN7vq/NfsAo5MnhFt6Y8g71WcDXW9I5ggVCYHqlH0xE12RJ1N5SIwGBpJ3UPTVOKa41IssGS5z+Vhhs1SdHo9okxXPXzcf4AY45Ve6EAAAA='
input = StringIO.new(str)
puts Zlib::GzipReader.new(input).read

这是我得到的输出

/Users/duke/.rvm/rubies/jruby-1.7.23/bin/jruby --1.9 -e $stdout.sync=true;$stderr.sync=true;load($0=ARGV.shift) /Users/duke/RubymineProjects/untitled/gzip_test.rb
Zlib::GzipFile::Error: not in gzip format
  initialize at org/jruby/ext/zlib/JZlibRubyGzipReader.java:156
         new at org/jruby/ext/zlib/JZlibRubyGzipReader.java:85
      (root) at /Users/duke/RubymineProjects/untitled/gzip_test.rb:6
        load at org/jruby/RubyKernel.java:1059
      (root) at -e:1

Process finished with exit code 1

压缩后的字符串是有效的。你可以在这里试试http://www.txtwizard.net/compression

【问题讨论】:

    标签: ruby gzip jruby zlib decoding


    【解决方案1】:

    您的 str 包含 Base64 编码数据。但是,由于Zlib::GzipReader 不会自行解码数据,而是需要原始二进制 gzip 数据,因此它失败了。

    您可以在创建 StringIO 对象之前手动解码数据:

    require 'base64'
    require 'stringio'
    require 'zlib'
    
    str = 'H4sIAAAAAAAA/y2NwQrDIBAFfyXstUbWNWrir5RSrEoQUi2JOZSQf6+EHt8wzDtgKd7VVPIG9n7AMwWwYhj1MBkkwtEwcN7vq/NfsAo5MnhFt6Y8g71WcDXW9I5ggVCYHqlH0xE12RJ1N5SIwGBpJ3UPTVOKa41IssGS5z+Vhhs1SdHo9okxXPXzcf4AY45Ve6EAAAA='
    raw = Base64.decode64(str)
    input = StringIO.new(raw)
    puts Zlib::GzipReader.new(input).read
    # => {"locations":[{"_id":1486497022087,"accuracy":50.0,"bearing":0.0,"datetime":"2017-02-07 22:50:22 +0300","latitude":55.660023,"longitude":37.759313,"speed":0.0}]}
    

    您链接到的网站也描述了这种行为(强调我的):

    这个简单的在线文本压缩工具是使用 gzip、bzip2 和 deflate 算法压缩纯文本并解压缩 压缩的 base64 字符串

    【讨论】:

      猜你喜欢
      • 2012-11-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-01-13
      • 2016-03-08
      • 1970-01-01
      相关资源
      最近更新 更多