tags:

views:

2715

answers:

5

Zlib::GzipReader can take "an IO, or -IO-lie, object." as it's input, as stated in docs.

Zlib::GzipReader.open('hoge.gz') {|gz|
    print gz.read
  }

  File.open('hoge.gz') do |f|
    gz = Zlib::GzipReader.new(f)
    print gz.read
    gz.close
  end

How should I ungzip a string?

+4  A: 

You need Zlib::Inflate for decompression of a string and Zlib::Deflate for compression

  def inflate(string)
    zstream = Zlib::Inflate.new
    buf = zstream.inflate(string)
    zstream.finish
    zstream.close
    buf
  end
dimus
+3  A: 

The above method didn't work for me.

I kept getting 'incorrect header check (Zlib::DataError)' error.

I tried decompressing a http response body to access xml.

The work around that I implemented was:

gz = Zlib::GzipReader.new(StringIO.new(resp.body.to_s))

xml = gz.read

Garth
+3  A: 

Zlib by default asumes that your compressed data contains a header. If your data does NOT contain a header it will fail by raising a Zlib::DataError.

You can tell Zlib to assume the data has no header via the following workaround:

def inflate(string)
  zstream = Zlib::Inflate.new(-Zlib::MAX_WBITS)
  buf = zstream.inflate(string)
  zstream.finish
  zstream.close
  buf
end
Marek de Heus
A: 

using (-Zlib::MAX_WBITS) , I got ERROR: invalid code lengths set and ERROR: invalid block type

The only following works for me , too.

Zlib::GzipReader.new(StringIO.new(response_body)).read

Thanks, Garth

john
A: 

I had a similar issue, and was able to workaround by using "deflate" with "nowrap=true" in my java code that was generating the string instead of the gzip library.

import java.util.zip.*;


private static String genDataGz (String jsonString) throws IOException
{   

        // Encode a String into bytes
        byte[] input = jsonString.getBytes("UTF-8");

        // Compress the bytes
        byte[] output = new byte[100];

        Deflater compresser = new Deflater(1, true);
        compresser.setInput(input);
        compresser.finish();
        int compressedDataLength = compresser.deflate(output);


        String stCompressed = Base64.encodeBytes(output);

        return stCompressed;
    }
ooleary