【问题标题】:Ruby: how to save file to UTF-16 Little EndianRuby:如何将文件保存为 UTF-16 Little Endian
【发布时间】:2011-06-17 23:00:21
【问题描述】:
我想用UTF-16 Little Endian将®保存成txt文件,我在某些方面测试过
1.下面的编码是UTF-8
$RegisterMark=[174].pack('U*')
file = File.new("C:/Output.txt","w")
file.puts $RegisterMark
file.close
2.下面的编码是UTF-16 Big Endian
require 'iconv'
$RegisterMark=[174].pack('U*')
$utf16RegisterMark =Iconv.conv('UTF-16', 'UTF-8', $RegisterMark )
file = File.new("C:/Output.txt","w")
file.puts $utf16RegisterMark
file.close
mentod Iconv.conv 不支持 UTF-16 LE 类型。
如何使用 UTF16 LE 保存 output.txt?
【问题讨论】:
标签:
ruby
unicode
utf-8
utf-16
utf-16le
【解决方案1】:
有点老套,但这对我有用。具体来说,我试图让 ruby 输出带有 BOM 的 UTF-16LE
## Adds BOM, albeit in a somewhat hacky way.
new_html_file = File.open(foo.txt, "w:UTF-8")
new_html_file << "\xFF\xFE".force_encoding('utf-16le') + some_text.force_encoding('utf-8').encode('utf-16le')
【解决方案2】:
最简单的方法是首先以 UTF-16LE 格式打开文件:
register_mark = "\00ua3" # or even just: register_mark = ®
File.open('C:/Output.txt', 'wt', encoding: 'UTF-16LE') do |f|
f.puts register_mark
end
这里的重要一点是显式指定文件的编码,使用options Hash 的File.new 方法(或在本例中为File.open)中的:encoding 键。这样,写入文件的字符串将自动转换,无论它们采用什么编码。
我还冒昧地将您的代码更改为更惯用的 Ruby 风格:
- Ruby 社区使用
snake_case,而不是CamelCase 作为变量和方法名称。
- 应避免使用全局变量,尤其是因为在您的示例中,无论如何它们都是多余的。
- 这里真的没必要用
Array#pack,只要写下你想要的。
- 尽可能使用
File.open 的块形式,即使出现错误或异常,它也会为您关闭文件。
- 处理文本文件时,应始终传递
t 修饰符。它在大多数操作系统上没有任何区别(这就是为什么不幸的是,大多数 Ruby 主义者忘记通过它的原因),但它在 Windows 上是至关重要,这就是你似乎正在使用的。