2017-02-08 9 views
0

zlibjrubyのgzipped文字列をデコードしようとしています。ここに最小の実例があります。Zlib :: GzipFile :: Error:gzip形式ではありません

require 'stringio' 
require 'zlib' 

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

そして、これは私がgzipで圧縮された文字列が有効である

/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

答えて

2

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}]} 

あなたも、この動作(強調鉱山)を説明するためにリンク先のウェブサイト:

This simple online text compression tool is compressing a plain text and decompressing compressed base64 string with gzip, bzip2 and deflate algorithms

関連する問題