Java 教程是为 JDK 8 编写的。本页中描述的示例和实践未利用在后续版本中引入的改进。
从概念上讲,每个 ResourceBundle 是一组共享相同基本名称的相关子类。下面的列表显示了一组相关的子类。ButtonLabel 是基本名称。基本名称后面的字符表示 Locale 的语言代码,国家/地区代码和变体。例如,ButtonLabel_en_GB 匹配由英语语言代码(en)和英国国家代码(GB)指定的 Locale。
ButtonLabel ButtonLabel_de ButtonLabel_en_GB ButtonLabel_fr_CA_UNIX
要选择适当的 ResourceBundle,请调用 ResourceBundle.getBundle 方法。以下示例为与法语,加拿大国家和 UNIX 平台匹配的 Locale 选择 ButtonLabel ResourceBundle。
Locale currentLocale = new Locale("fr", "CA", "UNIX");
ResourceBundle introLabels = ResourceBundle.getBundle(
                                 "ButtonLabel", currentLocale);
如果指定的 Locale 的 ResourceBundle 类不存在,getBundle 会尝试查找最接近的匹配项。例如,如果 ButtonLabel_fr_CA_UNIX 是所需的类,并且默认的 Locale 是 en_US,则 getBundle 将按以下顺序查找:
ButtonLabel_fr_CA_UNIX ButtonLabel_fr_CA ButtonLabel_fr ButtonLabel_en_US ButtonLabel_en ButtonLabel
请注意,getBundle 在选择基类(ButtonLabel) 之前,会根据默认的 Locale 查找类。如果 getBundle 无法在前面的类列表中找到匹配项,则会抛出 MissingResourceException。为避免抛出此异常,应始终提供不带后缀的基类。
抽象类 ResourceBundle 有两个子类:PropertyResourceBundle 和 ListResourceBundle。
PropertyResourceBundle 由属性文件支持。属性文件是包含可翻译文本的纯文本文件。属性文件不是 Java 源代码的一部分,它们只能包含 String 对象的值。如果需要存储其他类型的对象,请改用 ListResourceBundle。Backing a ResourceBundle with Properties Files 部分向你展示了如何使用 PropertyResourceBundle。
ListResourceBundle 类使用方便的列表管理资源。每个 ListResourceBundle 都由类文件支持。你可以将任何特定于语言环境的对象存储在 ListResourceBundle 中。要添加对其他 Locale 的支持,请创建另一个源文件并将其编译为类文件。Using a ListResource Bundle 部分有一个你可能会觉得有用的编码示例。
ResourceBundle 类非常灵活。如果你首先将特定于语言环境的 String 对象放在 PropertyResourceBundle 中,然后决定使用 ListResourceBundle,那么对你的代码没有任何影响。例如,以下对 getBundle 的调用将为相应的 Locale 获取 ResourceBundle,无论 ButtonLabel 是由类或属性文件支持:
ResourceBundle introLabels = ResourceBundle.getBundle(
                                 "ButtonLabel", currentLocale);
ResourceBundle 对象包含一组键值对。如果要从 ResourceBundle 中获取值,请指定键,该键必须是 String。该值是特定于语言环境的对象。以下示例中的键是 OkKey 和 CancelKey 字符串:
class ButtonLabel_en extends ListResourceBundle {
    // English version
    public Object[][] getContents() {
        return contents;
    }
    static final Object[][] contents = {
        {"OkKey", "OK"},
        {"CancelKey", "Cancel"},
    };
}
要从 ResourceBundle 中获取 OK String,你可以在调用 getString 时指定相应的键:
String okLabel = ButtonLabel.getString("OkKey");
属性文件包含键值对。键位于等号的左侧,值位于右侧。每对都在单独的行上。这些值只能表示 String 对象。以下示例显示名为 ButtonLabel.properties 的属性文件的内容:
OkKey = OK CancelKey = Cancel