【原理解释】
我们用API操作properties文件,如果获取的属性值是中文,为什么会出现乱码呢?
我们知道,如果编码(输出)和解码(读入)用的encoding是不一致的有可能会引起中文乱码问题,如果这两种encoding冲突,则你基本上就中奖了。看两个我们熟悉的eclipse提示:
1、假设如果我们创建properties文件用的encoding是GBK,我们写入了中文
2、Properties文件默认机制是采用ISO8859-1处理
3、我们用Properties.getProperty(String key)接口读取内容,这是时候得到的是乱码。因为想用ISO8859-1对GBK编码的内容进行解码
4、我们把用Properties.getProperty(String key)接口读取内容转换为创建properties文件时用的encoding(GBK)不就解决问题了
【代码示例】
2 /**
3 * util class
4 */
5 private PropertiesUtil() {}
6
7 /**
8 * 指定编码获取properties文件中的属性值(解决中文乱码问题)
9 *
10 * @param properties java.util.Properties
11 * @param key 属性key
12 * @return
13 */
14 public static String getProperty(Properties properties, String key, String encoding) throws UnsupportedEncodingException {
15 // param check
16 if (properties == null )
17 return null ;
18
19 // 如果此时value是中文,则应该是乱码
20 String value = properties.getProperty(key);
21 if (value == null )
22 return null ;
23
24 // 编码转换,从ISO8859-1转向指定编码
25 value = new String(value.getBytes( " ISO8859-1 " ), encoding);
26 return value;
27 }
28 }
如果你的应用创建中使用的系统默认编码,则如下转化:
PropertiesUtil.getProperty(properties, "TestKey", System.getProperty("file.encoding"));
PS:java中文乱码的问题会遇到不少,尤其是用字符流的时候。老早之前和乱码做过斗争,经验是要搞清楚产生乱码的基本原理,然后再修理它