在Ruby中将二进制文件作为字符串读取 [英] Read binary file as string in Ruby
问题描述
我需要一种简单的方法来获取 tar 文件并将其转换为字符串(反之亦然).有没有办法在 Ruby 中做到这一点?我最好的尝试是这样的:
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)
这不是同一个文件.执行 ls -l
显示文件大小不同,尽管它们非常接近(打开文件会显示大部分内容完整无缺).是我犯了一个小错误,还是有一种完全不同(但可行)的方法来实现这一目标?
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.
在那之后,您可能想要file.close
.如果你不这样做,file
在被垃圾收集之前不会被关闭,所以它在打开时会稍微浪费系统资源.
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屋!