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

2014-11-24 02:47:47 · 作者: · 浏览: 16
s SECONDARY.");
11 frCollator.setStrength(Collator.SECONDARY);
12 if (frCollator.compare(s1, s2) == 0)
13 System.out.println("s1 = s2");
14 System.out.println("The current strength is TERTIARY.");
15 frCollator.setStrength(Collator.TERTIARY);
16 if (frCollator.compare(s1, s2) == 0)
17 System.out.println("s1 = s2");
18 }
19 /* 输出结果如下:
20 The current strength is PRIMARY.
21 s1 = s2
22 The current strength is SECONDARY.
23 s1 = s2
24 The current strength is TERTIARY.
25 */
从输出结果中可以看出,当排序强度将为TERTIARY时,这两个字符将被视为不同的字符了。
6. 消息格式化:
1 //这里演示了MessageFormat的最基本用法:
2 // {0,time}: 0表示第0个占位符,time表示该占位符的格式为时间,如不指定style,按缺省格式显示。
3 // {1,number}: 1表示第1个占位符,number表示该占位符为数字。
4 static public void main(String[] args) {
5 String pattern = "The time is {0,time} and your lucky number is {1,number}.";
6 MessageFormat format = new MessageFormat(pattern);
7 Object objects[] = {new Date(),new Integer((int)(Math.random() * 1000))};
8 String formattedOutput = format.format(objects);
9 System.out.println(formattedOutput);
10
11 pattern = "The datetime is {0} and your lucky number is {1}.";
12 format = new MessageFormat(pattern);
13 //指定Locale
14 format.setLocale(Locale.US);
15 formattedOutput = format.format(objects);
16 System.out.println(formattedOutput);
17 format.setLocale(Locale.CHINA);
18 formattedOutput = format.format(objects);
19 System.out.println(formattedOutput);
20 }
21 /* 输出结果如下:
22 The time is 10:47:47 and your lucky number is 97.
23 The datetime is 8/28/11 10:47 AM and your lucky number is 97.
24 The datetime is 11-8-28 上午10:47 and your lucky number is 97.
25 */
Java针对Message中占位符的type,不仅提供了常规的number、time和date,还提供了choice格式,见如下例句:
String pattern = "On {2,date,long},{0} destroyed {1} houses and caused {3,number,currency} of damage";
注意占位符{1},尽管没有明确标注,仍然可以推测出它是number类型的。这里存在的主要问题是{1}后面的houses是复数格式,因此如果参数设置为1,则不符合英文的语法1 houses。再有就是如果参数设置为0,则更加奇怪"0 houses"。根据英文的语法规则,我们期待的格式是如果数量>=2,显示n houses,如果等于1,显示1 house,如果<=0,显示no house。如何完成这个功能呢?这里我们可以利用Java中给占位符提供的另外一种type: choice。其语法规则如下:
一个选择格式是由一个序列对组成,每一个对包括一个下限和一个格式字符串,下限和格式字符串由一个#符号分隔,对与对之间由符号|分隔。如:
{1,choice,0#no house|1#one house|2#{1} houses}
如果不使用选择格式,又希望实现刚刚说到的逻辑,就需要手工进行数量的判断,再根据数量的不同定义不同的pattern,如果使用选择格式,代码将会更加清晰明确,如:
String pattern = "On {2,date,long},{0} destroyed {1,choice,0#no house|1#one house|2#{1} houses} houses and caused {3,number,currency} of damage";
7. 字符集:
在进行byte和char之间的转换时,不同编码方式的字符集提供了不同的编码(encode)和解码(decode)规则,见如下代码:
1 public class MyTest {
2 public static void print(ByteBuffer bb) {
3 while (bb.hasRemaining())
4 System.out.print(bb.get() + " ");
5 System.out.println();
6 bb.rewind();
7 }
8
9 public static void main(String[] args) {
10 ByteBuffer bb = ByteBuffer.wrap(new byte[] { 0, 0, 0, 0, 0, 0, 0,
11 (byte) 'a' });
12 System.out.println("Initial Byte Buffer");
13 print(bb);
14 //提供了几种常用的字符集
15 Charset[] csets = { Charset.forName("UTF-16LE"),
16 Ch