文档

Java™教程
隐藏目录
ResourceBundle类简介
路径:国际化
课程:隔离特定区域设置的数据

关于ResourceBundle类

ResourceBundle与Locale的关联

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

ButtonLabel
ButtonLabel_de
ButtonLabel_en_GB
ButtonLabel_fr_CA_UNIX

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

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

如果指定的Locale没有对应的ResourceBundle类,getBundle方法会尝试找到最接近的匹配。例如,如果所需的类是ButtonLabel_fr_CA_UNIX,默认的Localeen_USgetBundle方法将按照以下顺序查找类:

ButtonLabel_fr_CA_UNIX
ButtonLabel_fr_CA
ButtonLabel_fr
ButtonLabel_en_US
ButtonLabel_en
ButtonLabel

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

ListResourceBundle和PropertyResourceBundle子类

抽象类ResourceBundle有两个子类:PropertyResourceBundleListResourceBundle

PropertyResourceBundle是由属性文件支持的。属性文件是一个包含可翻译文本的纯文本文件。属性文件不属于Java源代码的一部分,它们只能包含String对象的值。如果需要存储其他类型的对象,请使用ListResourceBundle。在使用属性文件支持ResourceBundle一节中,您将了解如何使用PropertyResourceBundle

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

ResourceBundle类是灵活的。如果你首先将特定于语言环境的String对象放入PropertyResourceBundle中,然后决定改用ListResourceBundle,对你的代码没有任何影响。例如,下面对getBundle的调用将检索到适当语言环境的ResourceBundle,无论ButtonLabel是由类支持还是由属性文件支持:

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

键值对

ResourceBundle对象包含一个键值对数组。当你想要从ResourceBundle中检索值时,你需要指定键,键必须是一个String。值是特定于语言环境的对象。下面的示例中,OkKeyCancelKey是键的字符串:

class ButtonLabel_en extends ListResourceBundle {
    // 英文版本
    public Object[][] getContents() {
        return contents;
    }
    static final Object[][] contents = {
        {"OkKey", "OK"},
        {"CancelKey", "Cancel"},
    };
}

要从ResourceBundle中检索OK字符串,你需要在调用getString时指定适当的键:

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

属性文件包含键值对。键在等号的左侧,值在右侧。每对键值对占据一行。值只能表示String对象。下面的示例显示了名为ButtonLabel.properties的属性文件的内容:

OkKey = OK
CancelKey = Cancel

上一页: 隔离与区域特定数据
下一页: 准备使用ResourceBundle