2014-11-03 207 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

相關問題