properties 中文亂碼問題的解決
在用properties處理配置信息時,發現有時出現中文亂碼的問題,后經查資料得知是由於編碼不一致引起的。於是解決之。
【原理解釋】
我們用 API操作properties文件,如果獲取的屬性值是中文,為什么會出現亂碼呢?
我們知道,如果編碼(輸出)和解碼(讀入)用的encoding是不一致的有可能會引起中文亂碼問題,如果這兩種encoding沖突,則你基本上就中獎了。1、假設如果我們創建properties文件用的encoding是GBK,我們寫入了中文
2、Properties文件默認機制是采用ISO8859-1處理
3、我們用Properties.getProperty(String key)接口讀取內容,這是時候得到的是亂碼。因為想用ISO8859-1對GBK編碼的內容進行解碼
4、我們把用Properties.getProperty(String key)接口讀取內容轉換為創建properties文件時用的encoding(GBK)不就解決問題了
【代碼示例】
public class PropertiesUtil { /** * util class */ private PropertiesUtil() {} /** * 指定編碼獲取properties文件中的屬性值(解決中文亂碼問題) * * @param properties java.util.Properties * @param key 屬性key * @return */ public static String getProperty(Properties properties, String key, String encoding) throws UnsupportedEncodingException { //param check if (properties == null) return null; // 如果此時value是中文,則應該是亂碼 String value = properties.getProperty(key); if (value == null) return null; // 編碼轉換,從ISO8859-1轉向指定編碼 value = new String(value.getBytes("ISO8859-1"), encoding); return value; } }
如果你的應用創建中使用的系統默認編碼,則如下轉化:
PropertiesUtil.getProperty(properties, "TestKey", System.getProperty("file.encoding"));
PS:java中文亂碼的問題會遇到不少,尤其是用字符流的時候。老早之前和亂碼做過斗爭,經驗是要搞清楚產生亂碼的基本原理,然后再修理它
<轉:http://wangfc123.blog.163.com/blog/static/157468012010324101137219/>
add 2013-04-24 21:57:22
今天發現eclipse里面可以直接通過properties Editor來打開properties文件,這樣寫進去的就是utf-8編碼的漢字了