2014-01-03

Ruby Gzip / Zip Stream

just code

require 'zip' #gem 'rubyzip'
require 'zlib'
require 'stringio'

##gzip_reader

  strio = StringIO.new(gzip_body)
  Zlib::GzipReader.new(strio).read

#=> ori_body


##gzip_writer

  strio = StringIO.new("")
  gz = Zlib::GzipWriter.new(strio)
  gz.write("foobar")
  gz.close
  strio.string

#=> gzip_body


##zip_io_reader

  str_io = StringIO.new(zip_body)
  file = {}
  Zip::InputStream.open(zip_io) do |io|
    while (entry = io.get_next_entry)
      file[entry.name] = io.read
    end
  end

#=> file = {:file_name => file_body}


##zip_io_writer

  #file = [:file_name => file_body]
  file = {}
  strio = Zip::OutputStream.write_buffer do |io|
    file.each_pair do |file_name , file_body|
      io.put_next_entry(file_name)
      io.write(file_body)
    end
  end
  strio.string

#=> zip_body

沒有留言:

張貼留言