使用Ruby自动打开一个二进制文件 [英] Automatically open a file as binary with Ruby
问题描述
实际上,不完整的。虽然在Unix文件系统中没有文本模式是真的,但Ruby确实在以二进制和非二进制模式打开文件方面有所作为:
s = File.open('/ tmp / test.jpg','r'){| io | io.read}
s.encoding
=> #<编码:UTF-8是氢。
不同于(注意rb
)
s = File.open('/ tmp / test.jpg','rb'){| io | io.read}
s.encoding
=> #<编码:ASCII-8BIT>
后者,作为 docs 说,将外部编码设置为ASCII-8BIT,它告诉Ruby不尝试以UTF-8解释结果。您可以通过使用 s.force_encoding('ASCII-8BIT')
明确设置编码来实现相同的操作。如果您想将二进制字符串读入字符串并将其移动(例如将其保存到数据库等),则这是关键。
I'm using Ruby 1.9 to open several files and copy them into an archive. Now there are some binary files, but some are not. Since Ruby 1.9 does not open binary files automatically as binaries, is there a way to open them automatically anyway? (So ".class" would be binary, ".txt" not)
Actually, the previous answer by Alex D is incomplete. While it's true that there is no "text" mode in Unix file systems, Ruby does make a difference between opening files in binary and non-binary mode:
s = File.open('/tmp/test.jpg', 'r') { |io| io.read }
s.encoding
=> #<Encoding:UTF-8>
is different from (note the "rb"
)
s = File.open('/tmp/test.jpg', 'rb') { |io| io.read }
s.encoding
=> #<Encoding:ASCII-8BIT>
The latter, as the docs say, set the external encoding to ASCII-8BIT which tells Ruby to not attempt to interpret the result at UTF-8. You can achieve the same thing by setting the encoding explicitly with s.force_encoding('ASCII-8BIT')
. This is key if you want to read binary into a string and move them around (e.g. saving them to a database, etc.).
这篇关于使用Ruby自动打开一个二进制文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!