我有这个代码,运行Ruby 2.3.1:
str = "麦克风访问被拒绝"
puts str.encoding #=> "UTF-8"
conv = Encoding::Converter.new("UTF-8", "UTF-16LE")
str = conv.convert(str)
puts str.encoding #=> "UTF-16LE"
Zlib::GzipWriter.open("test.gz", encoding: "UTF-16LE") do |gz|
puts str.encoding #=> "UTF-16LE"
gz.write(str)
end
Zlib::GzipReader.open("test.gz") do |gz|
puts gz.read.encoding #=> ASCII-8BIT
gz.read
end
并返回[无效编码]
如何以保持编码为UTF-16LE的方式保存文件?
答案 0 :(得分:3)
就我而言(并由文档确认),您无法向.open
- 函数发送选项哈希值。您必须先使用Zlib::GzipWriter.new(io, level = nil, strategy = nil, options = {})
创建对象,如Docs中所述。
require 'zlib'
str = "麦克风访问被拒绝"
conv = Encoding::Converter.new("UTF-8", "UTF-16LE")
str = conv.convert(str)
p str
File.open('test.gz', 'w') do |f|
gz = Zlib::GzipWriter.new(f, nil, nil, encoding: 'UTF-16LE' )
gz.write str
gz.close
end
File.open('test.gz') do |f|
gz = Zlib::GzipReader.new(f, { encoding: 'UTF-16LE' })
p gz.read
gz.close
end
此代码输出:
\u9EA6\u514B\u98CE\u8BBF\u95EE\u88AB\u62D2\u7EDD
\u9EA6\u514B\u98CE\u8BBF\u95EE\u88AB\u62D2\u7EDD
(更新 - 修复整个示例,正常工作)