`

关于java.util.Properties读取中文乱码的正确解决方案(不要再用native2ascii.exe了)

阅读更多

 

从Spring框架流行后,几乎根本不用自己写解析配置文件的代码了,
但近日一个基础项目(实在是太基础,不能用硕大繁琐的Spring),

碰到了用java.util.Properties读取中文内容(UTF-8格式)的配置文件,发生中文乱码的现象,

 

Properties prop=new Properties();       
prop.load(Client.class.getClassLoader().getResourceAsStream("config.properties"));

 

习惯性google了一下,网上大多数文章都是让大家用native2ascii.exe转换 这样的解决方案,一开始还差点被懵住了,以为只能使用这样的绕弯子方法。。。

 

但关键是,太绕了! 如果每次都用native2ascii.exe将中文转换成\uXXXX\uXXXX这样的,麻烦先不说,转换完后的文件完全不可读!!!这基本上是不可忍受的!
(虽然也能用native2ascii.exe转换回来,但同样,麻烦!)

冷静下来后,突然想起来,还是初学java时看过,java.io包中 Reader/Writer和Stream的区别。
(年代久远,具体细节忘记了,大概是:Reader/Write是处理编码文本的,而InputStream/OutputStream只把数据当作2进制流

正确解决方案

 

Properties prop=new Properties();       
prop.load(new InputStreamReader(Client.class.getClassLoader().getResourceAsStream("config.properties"), "UTF-8"));       

 

其中“UTF-8”,用于明确指定.properties文件的编码格式(不指定则默认使用OS的,这会造成同一份配置文件同一份代码,在linux和windows上、英文windows和中文windows之间的表现都不一致),这个参数应该和具体读取的properties文件的格式匹配。 

 

这个东西实在是基础,本来没啥好说的;但是网上流传的关于那个绕弯方法的文章太多了,太误导人了,还是写一下以正视听吧。

 

-------------------------------------------------------

后续:这两天发现,使用这种方法要注意一下,在linux下开发的.properties,如果要用到windows上,需要先用unix2dos 转换一下,否则可能发生配置项丢失的现象(可能是linux下的\r到了windows下不被Reader识别)。

 

5
4
分享到:
评论
6 楼 hft24dq 2016-02-16  
下面这种写法更好一些
String path = "d://properties.properties";
        Properties p = new Properties();
        Reader inStream = new InputStreamReader(new FileInputStream(path), "UTF-8");
        p.load(inStream);
5 楼 pig345 2011-11-09  
wangboak 写道
我想问下,这个
prop.load(new InputStreamReader(Client.class.getClassLoader().getResourceAsStream("config.properties"), "UTF-8"));  

中间的 new InputStreamReader 需要关闭吗?需要的话 怎么关闭?


上面只是个演示代码,你可以这样:
Properties prop = new Properties();
InputStream stream = Client.class.getClassLoader().getResourceAsStream("config.properties");
Reader reader = null;
try {
reader = new InputStreamReader(stream, "UTF-8");
prop.load(reader);
} catch (IOException e) {

// TODO 错误处理

} finally{
if (null != reader){
try {
reader.close();
} catch (IOException e) {
// ignore
}
}
}
4 楼 wangboak 2011-11-04  
我想问下,这个
prop.load(new InputStreamReader(Client.class.getClassLoader().getResourceAsStream("config.properties"), "UTF-8"));  

中间的 new InputStreamReader 需要关闭吗?需要的话 怎么关闭?
3 楼 pig345 2010-12-07  
xchao 写道
方法好是好,

不过我的怎么

prop.load(new InputStreamReader(Client.class.getClassLoader().getResourceAsStream("config.properties"), "UTF-8"));

load()方法没有这样参数列表的实现呢?

你用的是[img][/img][img]


你写错了,中间缺少new InputStreamReader(, "UTF-8"),这个reader才是关键阿!
2 楼 xchao 2010-12-02  
方法好是好,

不过我的怎么

prop.load(new InputStreamReader(Client.class.getClassLoader().getResourceAsStream("config.properties"), "UTF-8"));

load()方法没有这样参数列表的实现呢?

你用的是[img][/img][img]
1 楼 minfirefox 2010-08-05  


谢谢了!

相关推荐

Global site tag (gtag.js) - Google Analytics