1 // 目標(biāo):使用Properties讀取屬性文件中的內(nèi)容。 2 // 1、創(chuàng)建properties對(duì)象 3 Properties properties = new Properties(); 4 5 6 // 2、使用properties對(duì)象加載屬性文件中的鍵值對(duì)數(shù)據(jù)。 7 properties.load(new FileInputStream("day10-special-file-log\\src\\users.properties")); 8 9 // 3、確認(rèn)是否讀取出來了 10 System.out.println(properties); 11 12 // 4、根據(jù)鍵取值 13 String pwd = properties.getProperty("admin"); 14 System.out.println(pwd); 15 16 properties.forEach((k , v) -> { 17 System.out.println(k + "=" + v); 18 } );
?
day10-special-file-log\\src\\users.properties文件里面的內(nèi)容如下:
?期望輸出應(yīng)該和上面文件的內(nèi)容一樣,結(jié)果中文內(nèi)容輸出的是一堆亂碼:?1 ?????????=minmin 2 ??¨è?·è?¥=miejue 3 èμμ???=wuji 4 admin=123456?
可如果將上面??properties.load(new FileInputStream("day10-special-file-log\\src\\users.properties"));換成?properties.load(new FileReader("day10-special-file-log\\src\\users.properties"));就能正常輸出中文了,那這是什么原因呢?
其實(shí)properties文件中的中文亂碼問題主要有以下幾個(gè)原因:
1.properties文件的編碼格式和Java代碼的編碼格式不一致。properties文件默認(rèn)使用ISO-8859-1編碼,而Java代碼可能使用UTF-8或GBK等編碼。這樣在讀取或?qū)懭雙roperties文件時(shí),就會(huì)出現(xiàn)中文字符無法正確解析的情況。
2.properties文件中的中文字符沒有經(jīng)過轉(zhuǎn)換。properties文件只能存儲(chǔ)ASCII字符,所以如果要使用中文字符,就需要將其轉(zhuǎn)換為Unicode編碼??梢允褂胣ative2ascii.exe工具或者IDE的插件來實(shí)現(xiàn)這個(gè)轉(zhuǎn)換。
3.在Java代碼中指定字符集。在使用FileInputStream或FileWriter等類來讀取或?qū)懭雙roperties文件時(shí),需要指定相應(yīng)的字符集,例如UTF-8??梢允褂肐nputStreamReader或OutputStreamWriter等類來包裝FileInputStream或FileWriter,并傳入相應(yīng)的字符集參數(shù)。
?
而properties.load(new FileReader(file))能正常讀取的原因是,F(xiàn)ileReader默認(rèn)使用了與properties文件相同的字符編碼,即UTF-8。這樣就可以正確地解析文件中的中文字符,而不會(huì)出現(xiàn)亂碼。
可以使用InputStreamReader或OutputStreamWriter等類來包裝FileInputStream或FileWriter,并傳入相應(yīng)的字符集參數(shù)
示例代碼:文章來源:http://www.zghlxwxcb.cn/news/detail-623627.html
// 讀取文件時(shí)指定UTF-8編碼 Properties p = new Properties(); p.load(new InputStreamReader(new FileInputStream("config.properties"), "UTF-8")); // 寫入文件時(shí)指定UTF-8編碼 Properties p = new Properties(); p.setProperty("name", "李芳"); p.store(new OutputStreamWriter(new FileOutputStream("config.properties"), "UTF-8"), null);
?文章來源地址http://www.zghlxwxcb.cn/news/detail-623627.html
到了這里,關(guān)于Java中properties文件中的中文亂碼問題的文章就介紹完了。如果您還想了解更多內(nèi)容,請(qǐng)?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!