Ruby 中的 Zlib 解压缩 .gz [英] Zlib in Ruby to uncompress .gz

查看:34
本文介绍了Ruby 中的 Zlib 解压缩 .gz的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个包含 XML 文档的 .gz 文件.有谁知道如何正确使用 Zlib?到目前为止,我有以下代码:

I have a .gz file that contains an XML document. Does anyone know how to use Zlib properly? So far, I have the following code:

require 'zlib'
Zlib::GzipReader.open('PRIDE_Exp_Complete_Ac_1015.xml.gz') { |gz|
    g = File.new("PRIDE_Exp_Complete_Ac_1015.xml", "w")
      g.write(gz)
      g.close()
}

但这会创建一个空白的 .xml 文档.有谁知道我该如何正确地做到这一点?

But this creates a blank .xml document. Does anyone know how I can properly do this?

推荐答案

Zlib::GzipReader 的工作方式与 Ruby 中大多数类似 IO 的类一样.您有一个 open 调用,当您将一个块传递给它时,该块将收到类似 IO 的对象.认为这是在块期间对文件或资源执行某些操作的便捷方式.

Zlib::GzipReader works like most IO-like classes do in Ruby. You have an open call, and when you pass a block to it, the block will receive the IO-like object. Think of it is convenient way of doing something with a file or resource for the duration of the block.

但这意味着在您的示例中 gz 是一个类似 IO 的对象,而不是您所期望的 gzip 文件的内容.您仍然需要从中 read 来实现.最简单的解决方法是:

But that means that in your example gz is an IO-like object, and not actually the contents of the gzip file, as you expect. You still need to read from it to get to that. The simplest fix would then be:

g.write(gz.read)

请注意,这会将未压缩 gzip 的全部内容读入内存.

Note that this will read the entire contents of the uncompressed gzip into memory.

如果您真正要做的只是从一个文件复制到另一个文件,您可以使用更高效的 IO.copy_stream 方法.您的示例可能如下所示:

If all you're really doing is copying from one file to another, you can use the more efficient IO.copy_stream method. Your example might then look like:

Zlib::GzipReader.open('PRIDE_Exp_Complete_Ac_1015.xml.gz') do | input_stream |
  File.open("PRIDE_Exp_Complete_Ac_1015.xml", "w") do |output_stream|
    IO.copy_stream(input_stream, output_stream)
  end
end

在幕后,这将尝试使用 Linux 上某些特定情况下可用的 sendfile 系统调用.否则,它将一次复制 16KB 的快速 C 代码块.这是我从 Ruby 1.9.1 源代码中学到的.

Behind the scenes, this will try to use the sendfile syscall available in some specific situations on Linux. Otherwise, it will do the copying in fast C code 16KB blocks at a time. This I learned from the Ruby 1.9.1 source code.

这篇关于Ruby 中的 Zlib 解压缩 .gz的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆