关于 ResourceBundle 类

原文: https://docs.oracle.com/javase/tutorial/i18n/resbundle/concept.html

ResourceBundle 如何与区域设置相关联

从概念上讲,每个ResourceBundle是一组共享相同基本名称的相关子类。下面的列表显示了一组相关的子类。 ButtonLabel是基本名称。基本名称后面的字符表示语言代码,国家/地区代码和Locale的变体。例如,ButtonLabel_en_GB匹配英语(en)语言代码和英国国家代码(GB)指定的Locale

  1. ButtonLabel
  2. ButtonLabel_de
  3. ButtonLabel_en_GB
  4. ButtonLabel_fr_CA_UNIX

要选择适当的ResourceBundle,请调用ResourceBundle.getBundle方法。以下示例为Locale选择与法语,加拿大国家和 UNIX 平台匹配的ButtonLabel ResourceBundle

  1. Locale currentLocale = new Locale("fr", "CA", "UNIX");
  2. ResourceBundle introLabels = ResourceBundle.getBundle(
  3. "ButtonLabel", currentLocale);

如果指定的LocaleResourceBundle类不存在,getBundle会尝试查找最接近的匹配项。例如,如果ButtonLabel_fr_CA_UNIX是所需的类且默认Localeen_USgetBundle将按以下顺序查找类:

  1. ButtonLabel_fr_CA_UNIX
  2. ButtonLabel_fr_CA
  3. ButtonLabel_fr
  4. ButtonLabel_en_US
  5. ButtonLabel_en
  6. ButtonLabel

请注意,getBundle在选择基类(ButtonLabel)之前)根据默认Locale查找类。如果getBundle在前面的类列表中找不到匹配项,则会抛出MissingResourceException。避免抛出此异常,应始终提供没有后缀的基类。

ListResourceBundle 和 PropertyResourceBundle 子类

抽象类ResourceBundle有两个子类:PropertyResourceBundleListResourceBundle

PropertyResourceBundle由属性文件支持。属性文件是包含可翻译文本的纯文本文件。属性文件不是 Java 源代码的一部分,它们只能包含String对象的值。如果需要存储其他类型的对象,请改用ListResourceBundle使用属性文件备份 ResourceBundle 部分向您展示如何使用PropertyResourceBundle

ListResourceBundle类使用方便的列表管理资源。每个ListResourceBundle都有一个类文件支持。您可以在ListResourceBundle中存储任何特定于语言环境的对象。要添加对其他Locale的支持,请创建另一个源文件并将其编译为类文件。 使用 ListResource Bundle 部分有一个您可能会觉得有用的编码示例。

ResourceBundle类很灵活。如果您首先将特定于语言环境的String对象放在PropertyResourceBundle中,然后决定使用ListResourceBundle,则不会对您的代码产生任何影响。例如,以下对getBundle的调用将为适当的Locale检索ResourceBundle,无论ButtonLabel是由类还是属性文件备份:

  1. ResourceBundle introLabels = ResourceBundle.getBundle(
  2. "ButtonLabel", currentLocale);

键值对

ResourceBundle对象包含键值对的数组。如果要从ResourceBundle中检索值,请指定键,该键必须是String。该值是特定于语言环境的对象。以下示例中的键是OkKeyCancelKey字符串:

  1. class ButtonLabel_en extends ListResourceBundle {
  2. // English version
  3. public Object[][] getContents() {
  4. return contents;
  5. }
  6. static final Object[][] contents = {
  7. {"OkKey", "OK"},
  8. {"CancelKey", "Cancel"},
  9. };
  10. }

要从ResourceBundle中检索OK String,您可以在调用getString时指定相应的键:

  1. String okLabel = ButtonLabel.getString("OkKey");

属性文件包含键值对。键位于等号的左侧,值位于右侧。每对都在一条单独的线上。这些值可能仅代表String对象。以下示例显示名为ButtonLabel.properties的属性文件的内容:

  1. OkKey = OK
  2. CancelKey = Cancel