2014-11-03 205 views
0

我试图将二进制字段转换为文本,以便我可以将其输出到文件。内容是XML。到目前为止,我有...将二进制转换为文本,用于写入文件

File.open("public/test.txt", 'w') { |file| file.write(@report.catalog_xml) } 

错误抱怨从ASCII-8BIT到UTF-8的“\ xAC”。我已经尝试了元帅,Yaml转储,但仍然无法将纯文本作为输出

+1

尝试'wb'而不是'w' .. – 2014-11-03 18:32:55

+0

请显示'puts @ report.catalog_xml.encoding'的输出 – 2014-11-03 18:47:55

回答

1

您需要指定目标文件的编码以匹配数据源的编码。您可以确定如下假设#catalog_xml返回一个字符串:

@report.catalog_xml.encoding.name // => (e.g. ASCII-8BIT) 

有了这些知识,只需指定它,当你写入文件:

File.open("public/test.txt", "w:ASCII-8BIT") { |file| file.write(@report.catalog_xml) } 

你甚至可以插值值:

File.open("public/test.txt", "w:#{@report.catalog_xml.encoding.name}") { |file| file.write(@report.catalog_xml) } 
+0

谢谢,现在很有意义 – Atari2600 2014-11-03 19:01:03

相关问题