天天看點

ResourceBundle類讀取properties檔案

1.Properties與ResourceBundle類都可以讀取屬性檔案key/value的鍵值對

2.ResourceBundle類主要用來解決國際化和本地化問題,國際化時properties檔案命名規範:

  一般的命名規範是: 自定義名語言代碼國别代碼.properties,如果是預設的,直接寫為:自定義名.properties。

  例如:

  res_en_US.properties 

  res_zh_CN.properties                                       res.properties

  系統會自動選擇屬性資源檔案

3.使用:

  ResourceBundle bundle = ResourceBundle.getBundle("res", new Locale("zh", "CN"));

  new Locale(“zh”, “CN”)提供本地化資訊

  程式會首先在classpath下尋找res_zh_CN.properties檔案,若res_zh_CN.properties檔案不存在,則取找res_zh.properties,如還是不存在,繼續尋找res.properties,若都找不到就抛出異常。

  • 擷取ResourceBundle執行個體bundle 後可以通過下面的方法獲得本地化值。
  • getObject(String key);
  • getString(String key);
  • getStringArray(String key);

 如:bundle = ResourceBundle.getBundle("res", Locale.US);

  bundle = ResourceBundle.getBundle("res", Locale.getDefault());

  value= bundle.getString("key");

注意:ResourceBundle.getBundle("xxx", Locale.US);

  ResourceBundle類基于類讀取屬性檔案:将屬性檔案當作類,意味着屬性檔案必須放在包中(或src根目錄下),使用屬性檔案的全限定性類名而非路徑指代屬性檔案。

  ResourceBundle bundle = ResourceBundle.getBundle("com.rong.res.application");此時讀取的是com.rong.res包下的application.properties屬性檔案