2015年3月4日 星期三

Java ResourceBundle 多語系(本地化)

http://villebez.logdown.com/posts/2014/07/25/java-resourcebundle

這個類提供軟體國際化的捷徑。通過此類,可以使您所編寫的程式可以:
輕鬆地當地語系化或翻譯成不同的語言
一次處理多個語言環境
以後可以輕鬆地進行修改,支援更多的語言環境
這個類的作用就是讀取資源屬性檔(properties),然後根據.properties檔的名稱資訊(當地語系化資訊),匹配當前系統的國別語言資訊(也可以程式指定),然後獲取相應的properties檔的內容。
使用這個類,要注意的一點是,這個properties檔的名字是有規範的:一般的命名規範是:自訂名_語言代碼_國別代碼.properties,如果是默認的,直接寫為:自訂名.properties
例如:
example.properties
example_en_US.properties
example_zh_TW.properties
範例:
定義資源檔,放到src的根目錄下面
example_en_US.properties
aaa = Hello
example_zh_TW.properties
aaa = \u54C8\u56C9
public static void main(String[] args) {
         Locale locale1 = new Locale("zh", "TW"); 
     ResourceBundle resb1 = ResourceBundle.getBundle("example", locale1); 
     System.out.println(resb1.getString("aaa")); 

     Locale locale2 = new Locale("en", "US"); 
     ResourceBundle resb2 = ResourceBundle.getBundle("example", locale2); 
     System.out.println(resb2.getString("aaa")); 
}
執行結果:
哈囉
Hello
Eclipse Plugin:ResourceBundleEditor
好用的properties編輯工具,可以同時開啟不同語系的properties檔案,自動同步key,方便編輯多語系value,並會自動將文字轉換為Java Unicode Escape的格式

沒有留言:

張貼留言