使用Ruby自动打开一个二进制文件 [英] Automatically open a file as binary with Ruby

查看:127
本文介绍了使用Ruby自动打开一个二进制文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用Ruby 1.9打开几个文件并将其复制到存档中。现在有一些二进制文件,但有些不是。由于Ruby 1.9不能自动打开二进制文件作为二进制文件,有没有办法自动打开它们? (所以.class将是二进制的,.txt不是)

解决方案

实际上,不完整的。虽然在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屋!

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