Ruby:如何将文件保存到UTF-16 Little Endian [英] Ruby: how to save file to UTF-16 Little Endian

查看:162
本文介绍了Ruby:如何将文件保存到UTF-16 Little Endian的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用UTF-16 Little Endian将®保存到txt文件中,我已经进行了一些测试

I want to save ® into a txt file with UTF-16 Little Endian, I tested in some ways

1.下面的编码为UTF-8

1.The encoding below is UTF-8

$RegisterMark=[174].pack('U*')
file = File.new("C:/Output.txt","w")
file.puts $RegisterMark
file.close

2.下面的编码为UTF-16 Big Endian

2.The encoding below is 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类型.

The mentod Iconv.conv doesn't suport UTF-16 LE type.

如何使用UTF16 LE保存output.txt?

How can I save output.txt with UTF16 LE?

推荐答案

最简单的方法是首先以UTF-16LE格式打开文件:

The easiest way is to just open the file as UTF-16LE in the first place:

register_mark = "\00ua3" # or even just: register_mark = ®

File.open('C:/Output.txt', 'wt', encoding: 'UTF-16LE') do |f|
  f.puts register_mark
end

这里重要的一点是,使用File.new方法的options Hash中的:encoding键(或在本例中为File.open)显式指定文件的编码.这样,写入文件的字符串将自动转换,无论它们采用哪种编码.

The important bit here is to explicitly specify the encoding of the file, using the :encoding key in the options Hash of the File.new method (or in this case, File.open). That way, strings written to the file will be converted automatically, no matter what encoding they are in.

我还自由地将代码更改为更惯用的Ruby风格:

I also took the liberty of changing your code to a more idiomatic Ruby style:

  • Ruby社区使用snake_case而不是CamelCase作为变量和方法名称.
  • 应避免使用全局变量,特别是因为在您的示例中,全局变量完全是多余的.
  • 实际上不需要在这里使用Array#pack,只需写下您想要的内容即可.
  • 尽可能使用File.open的块形式,即使出现错误或异常,它也会为您关闭文件.
  • 在处理文本文件时,应始终通过t修饰符.在大多数操作系统上,它没有任何区别(不幸的是,这就是为什么大多数Ruby主义者忘记通过它的原因),但是在Windows上,它是关键的,这就是您似乎正在使用的.
  • The Ruby community uses snake_case, not CamelCase for variable and method names.
  • Global variables should be avoided, especially since in your example, they are totally superfluous anyway.
  • There's really no need to use Array#pack here, just write down what you want.
  • Whenever possible, use the block form of File.open, which will take care of closing the file for you, even in the case of an error or exception.
  • When dealing with text files, you should always pass the t modifier. It doesn't make any difference on most operating systems (which is why, unfortunately, most Rubyists forget to pass it), but it is crucial on Windows, which is what you appear to be using.

这篇关于Ruby:如何将文件保存到UTF-16 Little Endian的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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