使用属性文件备份 ResourceBundle

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

本节逐步介绍名为 PropertiesDemo的示例程序。

1.创建默认属性文件

属性文件是一个简单的文本文件。您可以使用几乎任何文本编辑器创建和维护属性文件。

您应该始终创建默认属性文件。该文件的名称以ResourceBundle的基本名称开头,以.properties后缀结尾。在PropertiesDemo程序中,基本名称为LabelsBundle。因此,默认属性文件称为LabelsBundle.properties。该文件包含以下行:

  1. # This is the default LabelsBundle.properties file
  2. s1 = computer
  3. s2 = disk
  4. s3 = monitor
  5. s4 = keyboard

请注意,在前面的文件中,注释行以井号(#)开头。其他行包含键值对。键位于等号的左侧,值位于右侧。例如,s2是对应于值disk的键。关键是任意的。我们可以将s2称为其他东西,如msg5diskID。但是,一旦定义,密钥就不应该改变,因为它在源代码中被引用。值可能会更改。实际上,当本地化程序创建新属性文件以容纳其他语言时,它们会将值转换为各种语言。

2.根据需要创建其他属性文件

要支持其他Locale,您的本地化程序将创建一个包含已翻译值的新属性文件。不需要更改源代码,因为您的程序引用了键而不是值。

例如,要添加对德语的支持,您的本地化程序将转换LabelsBundle.properties中的值并将它们放在名为LabelsBundle_de.properties的文件中。请注意,此文件的名称与默认文件的名称一样,以基本名称LabelsBundle开头,以.properties后缀结尾。但是,由于此文件适用于特定的Locale,因此基本名称后跟语言代码(de)。 LabelsBundle_de.properties的内容如下:

  1. # This is the LabelsBundle_de.properties file
  2. s1 = Computer
  3. s2 = Platte
  4. s3 = Monitor
  5. s4 = Tastatur

PropertiesDemo示例程序附带三个属性文件:

  1. LabelsBundle.properties
  2. LabelsBundle_de.properties
  3. LabelsBundle_fr.properties

3.指定区域设置

PropertiesDemo程序按如下方式创建Locale对象:

  1. Locale[] supportedLocales = {
  2. Locale.FRENCH,
  3. Locale.GERMAN,
  4. Locale.ENGLISH
  5. };

这些Locale对象应与前两个步骤中创建的属性文件匹配。例如,Locale.FRENCH对象对应于LabelsBundle_fr.properties文件。 Locale.ENGLISH没有匹配的LabelsBundle_en.properties文件,因此将使用默认文件。

4.创建 ResourceBundle

此步骤显示Locale,属性文件和ResourceBundle如何相关。要创建ResourceBundle,请调用getBundle方法,指定基本名称和Locale

  1. ResourceBundle labels = ResourceBundle.getBundle("LabelsBundle", currentLocale);

getBundle方法首先查找与基本名称和Locale匹配的类文件。如果找不到类文件,则检查属性文件。在PropertiesDemo程序中,我们使用属性文件而不是类文件来支持ResourceBundle。当getBundle方法找到正确的属性文件时,它返回包含属性文件中的键值对的PropertyResourceBundle对象。

5.获取本地化文本

要从ResourceBundle检索已翻译的值,请按如下方式调用getString方法:

  1. String value = labels.getString(key);

getString返回的String对应于指定的键。 String使用适当的语言,前提是指定的Locale存在属性文件。

6.遍历所有键

此步骤是可选的。调试程序时,可能需要为ResourceBundle中的所有键获取值。 getKeys方法返回ResourceBundle中所有键的Enumeration。您可以遍历Enumeration并使用getString方法获取每个值。以下代码行来自PropertiesDemo程序,显示了如何完成此操作:

  1. ResourceBundle labels = ResourceBundle.getBundle("LabelsBundle", currentLocale);
  2. Enumeration bundleKeys = labels.getKeys();
  3. while (bundleKeys.hasMoreElements()) {
  4. String key = (String)bundleKeys.nextElement();
  5. String value = labels.getString(key);
  6. System.out.println("key = " + key + ", " + "value = " + value);
  7. }

7.运行演示程序

运行PropertiesDemo程序会生成以下输出。前三行显示getString为各种Locale对象返回的值。当使用getKeys方法迭代键时,程序显示最后四行。

  1. Locale = fr, key = s2, value = Disque dur
  2. Locale = de, key = s2, value = Platte
  3. Locale = en, key = s2, value = disk
  4. key = s4, value = Clavier
  5. key = s3, value = Moniteur
  6. key = s2, value = Disque dur
  7. key = s1, value = Ordinateur