java properties文件乱码问题

  • Post author:
  • Post category:java



1. 打开properties文件,中文呈现乱码:


原因:文件格式问题,properties默认使用

ISO8859-1格式,中文显示,通用的是utf-8, 带中文的可改成gbk, gb2312. 这里改成         utf-8即可。



步骤:选中文件,右键–>properties–>resource,”text file coding”,默认是选择的defalut:”ISO8895-1″,修改成”other”,下拉       选择utf-8即可。



2.读取properties文件时出现乱码:eg:

String username=property.getProperty(key);




原因:


getProperty(key)是使用ISO8859-1来解码的,所以读取中文时会乱码,需要将读取出来的字符串从ISO8859-1再编码回         去,用文本的本身编码格式再解码。





解决方法:




在 String username=property.getProperty(key); 后增加:







resultName=new String(username.getBytes(“ISO-8859-1″),”gbk”);









直接使用resultName就行。










3.






(1)



在Properties.load中:







eg: java代码:
















FileInputStream isr = new FileInputStream(savePath);

Properties props = new Properties();

props.load(isr);


注意:isr 必须是文件字节流,不能是字符流,否则还是会乱码。(或者有解决办法,但是我还没找到!)


(2) 输出流:

eg: Java代码

OutputStreamWriter osw = new OutputStreamWriter(new FileOutputStream(savePath), “UTF-8”);

props.store(osw,”This is the System Config file,Please don’t delete or modify it!”);





版权声明:本文为lililiyunqiang原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。