2017-02-09 47 views
1

我有這樣的代碼,使用Ruby 2.3.1運行:紅寶石2.3寫入UTF-16LE gzip文件

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?

回答

2

就我而言(並且由Docs確認),您無法向.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 

(更新 - 修正整個例子,工作)