使用utf-8编码写入和读取文件 [英] Write and read a file with utf-8 encoding

查看:275
本文介绍了使用utf-8编码写入和读取文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在阅读所有与UTF-8相关的问题和博客文章,并且在test.rb文件中有以下示例:

I've been reading up on all the UTF-8 related questions and blog posts, and I've got the following example in a test.rb file:

# encoding: UTF-8
File.open("test.txt", "w") do |f|
  f.write "test © foo"
end

File.open("test.txt", "r") do |f|
  puts f.read
end

这很好用.是在文件中正确生成©符号,然后将©读回给我,然后将其打印在屏幕上.

this works perfectly. is produces the © symbol correctly in the file, and it reads the © back to me and prints it on the screen.

但是当我在实际项目中使用相同的代码时,会将其写入文件而不是©符号:\u00A9

but when I use this same code in my actual project, i get this written to the file instead of the © symbol: \u00A9

FWIW:对我的代码运行rspec(v1.2.9)测试时,我得到了这个结果.规范会生成一个带有©符号的文件,然后再读回该文件以检查其内容.

FWIW: I'm getting this result when running an rspec (v1.2.9) test against my code. the spec produces a file with a © symbol in it, and then reads the file back in to check the contents.

目前我正在Ruby 1.9.2中运行它,但是我还需要一直支持到Ruby 1.8.6.这是具有RubyInstaller.org版本的Ruby的Windows环境.

I'm running this in Ruby 1.9.2 at the moment, but I also need to support all the way back to Ruby 1.8.6. This is a Windows environment with RubyInstaller.org versions of Ruby.

推荐答案

如果我执行您的代码,则会收到特殊字符错误.你可以试试这个代码吗?

If i execute your code i get an error on the special character. Can you try this code ?

# encoding: UTF-8
File.open("test.txt", "w:UTF-8") do |f| 
  f.write "test \u00A9 foo" 
end 

#Encoding.filesystem = "UTF-8"
p Encoding.find("filesystem") 
File.open("test.txt", "r:UTF-8") do |f| 
  puts f.read 
end 

然后在我的Windows框上

On my windows box i then get

#<Encoding:Windows-1252>
test © foo

我不知道为什么在那儿.

I have no idea why the  is there..

这篇关于使用utf-8编码写入和读取文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆