Step By Step(Java 国际化篇)(八)

2014-11-24 02:47:47 · 作者: · 浏览: 9
te() };
8 MessageFormat formatter = new MessageFormat("");
9 formatter.setLocale(currentLocale);
10 formatter.applyPattern(messages.getString("template"));
11 String output = formatter.format(messageArguments);
12 System.out.println(output);
13 }
14
15 public static void main(String[] args) {
16 displayMessage(new Locale("en", "US"));
17 displayMessage(new Locale("de", "DE"));
18 }
19 }
20 /* 输出结果如下:
21 currentLocale = en_US
22 At 9:27 PM on August 29, 2011, we detected 7 spaceships on the planet Mars.
23 currentLocale = de_DE
24 Um 21:27 am 29. August 2011 haben wir 7 Raumschiffe auf dem Planeten Mars entdeckt.
25 */
以下示例结合了ChoiceFormat和ResourceBundle,资源文件内容如下:
File: ChoiceBundle_en_US.properties
noFiles = are no files
oneFile = is one file
multipleFiles = are {2} files
pattern = There {0} on {1}.

File: ChoiceBundle_fr_FR.properties
noFiles = n' y a pas des fichiers
oneFile = y a un fichier
multipleFiles = y a {2} fichiers
pattern = Il {0} sur {1}.
见代码如下:
1 public class MyTest {
2 static void displayMessages(Locale currentLocale) {
3 System.out.println("currentLocale = " + currentLocale.toString());
4 //1. 根据Locale的不同,获取不同的资源文件
5 ResourceBundle bundle = ResourceBundle.getBundle("ChoiceBundle",currentLocale);
6 MessageFormat messageForm = new MessageFormat("");
7 //2. 给MessageFormat对象设定locale,便于资源文件的定位。
8 messageForm.setLocale(currentLocale);
9 //3. 设定ChoiceFormat下限部分
10 double[] fileLimits = { 0, 1, 2 };
11 //4. 从资源文件中读取指定的key/value,之后再初始化ChoiceFormat的选择部分。
12 String[] fileStrings = { bundle.getString("noFiles"),
13 bundle.getString("oneFile"), bundle.getString("multipleFiles") };
14 ChoiceFormat choiceForm = new ChoiceFormat(fileLimits, fileStrings);
15 //5. 根据资源文件中“pattern”键值对来定义MessageFormat的pattern部分。
16 String pattern = bundle.getString("pattern");
17 //6. 定义MessageFormat.pattern的格式信息。
18 Format[] formats = { choiceForm, null, NumberFormat.getInstance() };
19 messageForm.applyPattern(pattern);
20 messageForm.setFormats(formats);
21 //7. 定义和formats对应的格式参数。
22 Object[] messageArguments = { null, "XDisk", null };
23 for (int numFiles = 0; numFiles < 4; numFiles++) {
24 //8. 重新设定格式参数中第0个和第2个参数的值,该值为被ChoiceFormat利用,
25 //并根据该参数值的不同选择不同的Choice字符串来替换。
26 messageArguments[0] = new Integer(numFiles);
27 messageArguments[2] = new Integer(numFiles);
28 //9. 开始格式化了。
29 String result = messageForm.format(messageArguments);
30 System.out.println(result);
31 }
32 }
33
34 public static void main(String[] args) {
35 displayMessages(new Locale("en", "US"));
36 displayMessages(new Locale("fr", "FR"));
37 }
38 }
39 /* 输出结果如下:
40 currentLocale = en_US
41 There are no files on XDisk.
42 There is one file on