使用属性文件备份 ResourceBundle
本节逐步介绍一个名为PropertiesDemo的示例程序。
1.创建默认属性文件
属性文件是一个简单的文本文件。您几乎可以使用任何文本编辑器来创建和维护属性文件。
您应该始终创建一个默认属性文件。该文件的名称以ResourceBundle
的基本名称开头,以.properties
后缀结尾。在PropertiesDemo
程序中,基本名称是LabelsBundle
。因此,默认属性文件称为LabelsBundle.properties
。该文件包含以下几行:
# This is the default LabelsBundle.properties file
s1 = computer
s2 = disk
s3 = monitor
s4 = keyboard
请注意,在前面的文件中,注解 行以井号(#)开头。其他行包含键值对。键位于等号的左侧,值位于右侧。例如,s2
是与值disk
对应的键。密钥是任意的。我们可以将s2
称为其他名称,例如msg5
或diskID
。但是,一旦定义,密钥就不应更改,因为它已在源代码中引用。值可以更改。实际上,当本地化人员创建新的属性文件以容纳其他语言时,它们会将值转换为各种语言。
2.根据需要创建其他属性文件
为了支持其他Locale
,本地化人员将创建一个包含转换后的值的新属性文件。不需要更改源代码,因为程序引用的是键,而不是值。
例如,要增加对德语的支持,您的本地化人员可以将值翻译成LabelsBundle.properties
并将它们放在名为LabelsBundle_de.properties
的文件中。请注意,此文件的名称与默认文件的名称一样,以基本名称LabelsBundle
开头,以.properties
后缀结尾。但是,由于此文件用于特定的Locale
,因此基本名称后跟语言代码(de
)。 LabelsBundle_de.properties
的内容如下:
# This is the LabelsBundle_de.properties file
s1 = Computer
s2 = Platte
s3 = Monitor
s4 = Tastatur
PropertiesDemo
示例程序附带三个属性文件:
LabelsBundle.properties
LabelsBundle_de.properties
LabelsBundle_fr.properties
3.指定语言环境
PropertiesDemo
程序创建Locale
对象,如下所示:
Locale[] supportedLocales = {
Locale.FRENCH,
Locale.GERMAN,
Locale.ENGLISH
};
这些Locale
对象应与前两个步骤中创建的属性文件匹配。例如,Locale.FRENCH
对象对应于LabelsBundle_fr.properties
文件。 Locale.ENGLISH
没有匹配的LabelsBundle_en.properties
文件,因此将使用默认文件。
4.创建 ResourceBundle
此步骤显示Locale
,属性文件和ResourceBundle
的关系。要创建ResourceBundle
,请调用getBundle
方法,并指定基本名称和Locale
:
ResourceBundle labels = ResourceBundle.getBundle("LabelsBundle", currentLocale);
getBundle
方法首先查找与基本名称和Locale
匹配的类文件。如果找不到类文件,则检查属性文件。在PropertiesDemo
程序中,我们使用属性文件而不是类文件来支持ResourceBundle
。 getBundle
方法找到正确的属性文件时,它将返回一个PropertyResourceBundle
对象,该对象包含来自属性文件的键/值对。
5.提取本地化文本
要从ResourceBundle
检索转换后的值,请按以下方式调用getString
方法:
String value = labels.getString(key);
getString
返回的String
对应于指定的密钥。 String
使用正确的语言,前提是存在针对指定Locale
的属性文件。
6.遍历所有键
此步骤是可选的。在调试程序时,您可能希望获取ResourceBundle
中所有键的值。 getKeys
方法返回ResourceBundle
中所有键的Enumeration
。您可以遍历Enumeration
并使用getString
方法获取每个值。来自PropertiesDemo
程序的以下代码行显示了如何完成此操作:
ResourceBundle labels = ResourceBundle.getBundle("LabelsBundle", currentLocale);
Enumeration bundleKeys = labels.getKeys();
while (bundleKeys.hasMoreElements()) {
String key = (String)bundleKeys.nextElement();
String value = labels.getString(key);
System.out.println("key = " + key + ", " + "value = " + value);
}
7.运行演示程序
运行PropertiesDemo
程序将生成以下输出。前三行显示getString
为各种Locale
对象返回的值。当使用getKeys
方法遍历键时,程序将显示最后四行。
Locale = fr, key = s2, value = Disque dur
Locale = de, key = s2, value = Platte
Locale = en, key = s2, value = disk
key = s4, value = Clavier
key = s3, value = Moniteur
key = s2, value = Disque dur
key = s1, value = Ordinateur