Java讀properties檔案中文亂碼問題的解決方案

來源:互聯網
上載者:User

標籤:

java讀properties檔案,包含中文字元的主要有兩種:

1.key中包含中文字元的(value中也有可能包含)

2.key中不包含中文字元的(value中有可能包含)

 

1、key中包含中文字元

可以使用java內建工具native2ascii.exe(Java\jdk1.x.x\bin\native2ascii.exe),轉換檔編碼格式

樣本: native2ascii -encoding 8859_1 c:\a.properties c:\b.properties

即將 c:\a.properties檔案內容用8859_1轉碼,另存新檔c:\b.properties檔案。

命令格式: native2ascii -[options] [inputfile [outputfile]]

 

參數選項 options -reverse:將 Latin-1 或 Unicode 編碼轉為本地編碼 -encoding encoding_name:指定轉換時使用的編碼 inputfile:要轉換的檔案 outputfile:轉換後的檔案
互轉(-encoding,非英文內容(如中文)轉為編碼符 或 編碼符之間的轉換)
逆轉(-reverse,通常是將編碼符轉為非英文內容,或非英文內容之間的轉換)
逆轉時被轉的檔案編碼和本地編碼需一致:
樣本: 中文轉為 ISO 8859_1 編碼後,將 8859_1 碼轉為中文:
native2ascii -encoding 8859_1 c:\a.txt c:\b.txt,
將 a 用 8859_1 轉碼,存為 b (8859_1 碼)
native2ascii -encoding GBK c:\b.txt c:\c.txt,

將 b 用 GBK 轉碼,存為 c (GBK 碼)


native2ascii -reverse c:\c.txt c:\d.txt,
將 GBK 編碼 c 用本地編碼轉碼,存為 d (中文內容) 中文轉為 GBK 編碼後,將 GBK 碼轉為中文:

native2ascii -encoding GBK c:\a.txt c:\b.txt,
將 a 用 GBK 轉碼,存為 b (GBK 碼)

native2ascii -reverse c:\b.txt c:\c.txt,
將 GBK 編碼 b 用本地編碼轉碼,存為 c (中文內容)

做完上述操作後,讀取key中含有中文的properties,需有下面的轉碼:

String value = "中國";
String value2 = new String(value.getBytes(),"ISO-8859-1");
System.out.println(p.getProperty(value2));

2.key中不包含中文字元的,value中有中文

直接使用1中的:

String value = p.getProperty(key);
String value2 = new String(value.getBytes("ISO-8859-1"),"GBK");

Java讀properties檔案中文亂碼問題的解決方案

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.