Java I18n 简明教程
Java Internationalization - ResourceBundle Class
ResourceBundle 类用于存储与语言环境相关的文本和对象。我们通常使用属性文件来存储特定语言环境的文本并使用 ResourceBundle 对象来表示它们。以下是 Java 中基于应用程序使用特定语言环境的属性文件的步骤。
ResourceBundle class is used to store text and objects which are locale sensitive. Generally we use property files to store locale specific text and then represent them using ResourceBundle object. Following are the steps to use locale specific properties file in a java based application.
Step 1: Create Properties Files
假设我们需要英语语言环境的属性文件。然后创建一个属性文件名称为 XXX_en_US.properties,其中 XXX 是文件名称,而 en_US 表示英语 (美国) 的语言环境。
Suppose we need properties file for English locale. Then create a properties file name XXX_en_US.properties where XXX is the name of the file and en_US represents the locale for English(US).
Messages_en_US.properties
Messages_en_US.properties
message=Welcome to TutorialsPoint.COM!
现在,让我们为法语语言环境创建一个属性文件。然后创建一个名为 XXX_fr_FR.properties 的属性文件,其中 XXX 是文件名称,而 fr_FR 代表法语 (法国) 的语言环境。
Let’s now create properties file for French locale. Then create a properties file name XXX_fr_FR.properties where XXX is the name of the file and fr_FR represents the locale for French(France).
Messages_fr_FR.properties
Messages_fr_FR.properties
message=Bienvenue sur TutorialsPoint.COM!
在这里你可以发现键是相同的,但值在两个属性文件中属于特定语言环境。
Here you can figure out that the key is same but the value is locale specific in both the properties file.
Step 2: Create ResourceBundle Object
使用属性文件名称和语言环境通过以下语法创建 ResourceBundle 对象。
Create ResourceBundle object with properties file name and locale using following syntax.
ResourceBundle bundle = ResourceBundle.getBundle("Messages", Locale.US);
Step 3: Get the value from ResourceBundle Object
通过传递键从 ResourceBundle 对象获取值。
Get the value from ResourceBundle object by passing the key.
String value = bundle.getString("message");
Example
以下示例说明如何使用 ResourceBundle 对象从属性文件中显示特定语言环境的值。
Following example illustrate the use of ResourceBundle objects to display locale specific values from properties files.
import java.util.Locale;
import java.util.ResourceBundle;
public class I18NTester {
public static void main(String[] args) {
ResourceBundle bundle = ResourceBundle.getBundle("Messages", Locale.US);
System.out.println("Message in "+Locale.US +": "+bundle.getString("message"));
bundle = ResourceBundle.getBundle("Messages", Locale.FRANCE);
System.out.println("Message in "+Locale.FRANCE +": "+bundle.getString("message"));
}
}
它将打印以下结果。
It will print the following result.
Message in en_US: Welcome to TutorialsPoint.COM!
Message in fr_FR: Bienvenue sur TutorialsPoint.COM!
Notes for Naming Conventions
以下是属性文件的命名约定。
Following are the naming conventions for the properties file.
-
For properties file mapped to default locale, no prefix is mandatory. message_en_US.properties is equivalent to message.properties.
-
For properties file mapped to locale, prefix can be attached in two ways. message_fr.properties is equivalent to message_fr_FR.properties.