2012-06-20 49 views
3

,我發現了以下錯誤:Ruby 1.9的Base64編碼的文件寫入錯誤

Encoding::UndefinedConversionError: "\x81" from ASCII-8BIT to UTF-8 

下面所有的Ruby 1.8.7的工作,所以我覺得這與Ruby 1.9的如何處理編碼做,但我不太清楚如何解決它。我目前正在使用Ruby 1.9.3。

decode_base64_content = Base64.decode64(content) 

    File.open("index.txt", "w") do |f| 
    f.write(decode_base64_content) 
    end 

其中內容是一樣的東西:

CgcZAAEAAABQcmVzZW50YXRpb24RMQAGSUIyQjdCNjBCLUZBRTMtMjVGMS1DQ0E1LTM1REM4NjBC 
MDlCRgYCBklBMjk2OTQ4MC0yMkQyLURENzMtQUY5Ni1DNURDMDIyQTVFRjkGBAZJNUJCRTI3REYt 
Q0QyRC03NkY0LTk1MUMtQzYxRkYxQjgxN0Y4BgYGSTg0QjM3M0FGLTVFNjEtMkMwMy1DMTBCLUNB 
MUZCMDY0Q0NERQYIBkkwOTIwNDRBRC02QTQ5LTg0NzEtMzc5QS0yRjQxMzU2MUY0OUQGCgZJODlC 
NDczOTUtOTk1MS01OTk1LTk4NDctNkU1NjI4RjhGNjYzBgwGSThCQ0RFM0VDLUMyREItMDkyNy1G 
NTFFLTJGNDE4OEMzNURDMwYOBklGMDk5QkRDOC1GOEFDLTg1QjEtMjgzMC0yRjQ5RkZFMDFCNUEG 
EAZJNTJCOEQ3RUItMzZEQi1CMjNELUU2MTYtMkY0QjUxNDIwMjBFBhIGSUM2RjkzNjgwLTFBNjMt 
NzU5Qi0yOEE5LTUwMDc2NjZCOEYyNgYUBkk2MDIwRjg4Ni1BQTk4LTRBNDQtQjZGNS1DNDAyMTMz 
NzEzOEQGFgZJRDFEMjcxMzYtQTkwQy0xRDBBLTc4RjAtQ0ExRUFCQzgzRUE1BhgGSUZBRDQzMjI1 
LTUwODctNENEMy1ENjkzLUQ4Qzg0NDc3RTMyRAYaBklFMjc5NjA5Mi0xNUYzLUY4NkItMEFBQi0x 
MUEzQjIwNEFBRTIGHAZJNERFNEYzNUItQzAyNy1DOTQ1LTY2MzUtMDE4NTZDRTdBMDM3Bh4GSUM4 
NjA4RkI4LUI4RDEtMjM5RS04ODY4LUNBMjIzNUUwNjk5MAYgBkk4QjcxOEFDRi03NEE0LTA4REQt 
QzZENC1DQTEyNDQwRTkzOUYGIgZJQjA3NTk0OEMtQzA3MS0wQTQ3LTYxNDQtNEU1OUIwN0QwQ0VF 
BiQGSUM2M0VFQkU1LUZFOEEtRUVDMC1GNDFFLTc3QTI3Qzg2RDE1OAYmBkk5QkQ2M0NEQi02NDg2 
LTM2OUQtMTY0NS0xMDIzMTQ5Njk1OUQGKAZJOTI3NDUzNDEtRUYzRC04MEU1LUZDQkUtQ0EyMTZG 
Q0FGRTcyBioGSUI3MzlFMTBFLTk2M0QtMDA0Ny1EMkU1LUNBMjA2ODM2MjZFNgYsBkk4RUY5QkZB 
Ni0wNDAyLTQwQUQtRjAxQi0xMTRBNDBFODMwRjMGLgZJQjY2N0YxODktNzQ4My05RkE4LTYwMDkt 

是持續〜3000線。

如何解決此轉換錯誤?上面的代碼片段工作,但在3000行的某處我認爲base64解碼方法使用無效編碼。謝謝!

+0

這將是有益的知道異常是否是由'Base64.decode64募集'電話或'f.write'調用。 – rewritten

+0

錯誤發生在f.write調用 – John

回答

9

鑑於"\x81"是控制字符,所以它不是任何手段文字,你應該打開文件的二進制:

File.open("index.txt", "wb") do |f| 
    f.write(decode_base64_content) 
end 
+3

完美!謝謝! – John

+1

對我也很有幫助! – poseid

+2

是「wb」「w:binary」的別名? – Krut