在Ruby中读取二进制文件作为字符串 [英] Read binary file as string in Ruby

查看:196
本文介绍了在Ruby中读取二进制文件作为字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要一个简单的方法来获取一个tar文件并将其转换为一个字符串(反之亦然)。有没有办法在Ruby中做到这一点?我最好的尝试是这样的:

  file = File.open(path-to-file.tar.gz)
contents =
file.each {| line |
内容<<行
}

我认为这足以将其转换为字符串,当我试图把它写回来像这样...

$ $ $ $ $ $ $ newFile = File.open(test.tar.gz ,w)
newFile.write(contents)

不一样文件。做 ls -l <​​/ code>显示文件大小不一,尽管它们非常接近(打开文件显示大部分内容完整)。是否有一个小错误,我做或完全不同(但可行)的方式来实现这一目标? 解决方案

首先,你应该打开文件作为二进制文件。然后你可以在一个命令中读取整个文件。

  file = File.open(path-to-file。 tar.gz,rb)
contents = file.read

你完整的文件在一个字符串中。

之后,你可能需要 file.close 。如果你不这样做, file 在被垃圾收集之前不会被关闭,所以在打开的时候系统资源会被轻微的浪费。 / p>

I need an easy way to take a tar file and convert it into a string (and vice versa). Is there a way to do this in Ruby? My best attempt was this:

file = File.open("path-to-file.tar.gz")
contents = ""
file.each {|line|
  contents << line
}

I thought that would be enough to convert it to a string, but then when I try to write it back out like this...

newFile = File.open("test.tar.gz", "w")
newFile.write(contents)

It isn't the same file. Doing ls -l shows the files are of different sizes, although they are pretty close (and opening the file reveals most of the contents intact). Is there a small mistake I'm making or an entirely different (but workable) way to accomplish this?

解决方案

First, you should open the file as a binary file. Then you can read the entire file in, in one command.

file = File.open("path-to-file.tar.gz", "rb")
contents = file.read

That will get you the entire file in a string.

After that, you probably want to file.close. If you don’t do that, file won’t be closed until it is garbage-collected, so it would be a slight waste of system resources while it is open.

这篇关于在Ruby中读取二进制文件作为字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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