Java读取properties文件中文乱码问题的解决
Java直接读取properties文件时,中文会是乱码,这时可以用Java\jdk1.x.x\bin<span style="color:red">native2ascii.exe工具。 例如,把f1.properties转换成f2.properties。
在cmd的当前目录下输入
native2ascii -encoding gbk f1.properties f2.properties
转换前f1.properties:
#编号=描述
cn=中国
转换后f2.properties:
#\u7f16\u53f7=\u63cf\u8ff0
cn=\u4e2d\u56fd
这样Java程序就可以正确识别中文了!
Properties prop=new Properties();
InputStream inputStream=new FileInputStream("E:\\f2.properties");
prop.load(inputStream);
String title=prop.getProperty("cn");
System.out.println(title);
转换前运行结果:
???ú
转换后运行结果:
中国
一楼的解决方案才是正解,什么转换为unicode的方法,无论是用native2ascii.exe,还是用eclispe提供的功能来转换,都只是治标不治本的。
这两个方法都不用了,直接在MyEclipse中编辑汉字,保存时自动保存为\u4e2d\u56fd码了!
好样的~谢谢啊~
实在忍不住了,网上太多这样的解决方案,可惜全部都是错误的(起码不是最优的)。 如果每次都用native2ascii.exe转换,麻烦先不说,转换完后的文件完全不可读!!!这基本上是不可忍受的!(虽然也能用native2ascii.exe转换回来,但 多 麻 烦 阿!)
难道大家都没有仔细学过java.io这个包? (当年初学java时看过,年代久远,具体的忘记了,大概是:Reader/Write是包含处理编码文本的,而InputStream/OutputStream只是处理2进制数据)
正确解决方案 Properties prop=new Properties();
prop.load(new InputStreamReader(new FileInputStream("E:\f2.properties")));