关于 ResourceBundle 类
原文: https://docs.oracle.com/javase/tutorial/i18n/resbundle/concept.html
ResourceBundle 如何与区域设置相关联
从概念上讲,每个ResourceBundle
是一组共享相同基本名称的相关子类。下面的列表显示了一组相关的子类。 ButtonLabel
是基本名称。基本名称后面的字符表示语言代码,国家/地区代码和Locale
的变体。例如,ButtonLabel_en_GB
匹配英语(en
)语言代码和英国国家代码(GB
)指定的Locale
。
ButtonLabel
ButtonLabel_de
ButtonLabel_en_GB
ButtonLabel_fr_CA_UNIX
要选择适当的ResourceBundle
,请调用ResourceBundle.getBundle
方法。以下示例为Locale
选择与法语,加拿大国家和 UNIX 平台匹配的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
。避免抛出此异常,应始终提供没有后缀的基类。
ListResourceBundle 和 PropertyResourceBundle 子类
抽象类ResourceBundle
有两个子类:PropertyResourceBundle
和ListResourceBundle
。
PropertyResourceBundle
由属性文件支持。属性文件是包含可翻译文本的纯文本文件。属性文件不是 Java 源代码的一部分,它们只能包含String
对象的值。如果需要存储其他类型的对象,请改用ListResourceBundle
。 使用属性文件备份 ResourceBundle 部分向您展示如何使用PropertyResourceBundle
。
ListResourceBundle
类使用方便的列表管理资源。每个ListResourceBundle
都有一个类文件支持。您可以在ListResourceBundle
中存储任何特定于语言环境的对象。要添加对其他Locale
的支持,请创建另一个源文件并将其编译为类文件。 使用 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