MessageFormat妙用

java.text.MessageFormat类

MessageFormat提供一种语言无关的方式来组装消息,它允许你在运行时刻用指定的参数来替换掉消息字符串中的一部分。你可以为MessageFormat定义一个模式,在其中你可以用占位符来表示变化的部分:

 Object[] arguments = {
     new Integer(7),
     new Date(System.currentTimeMillis()),
     "a disturbance in the Force"
 };

 String result = MessageFormat.format(
     "At {1,time} on {1,date}, there was {2} on planet {0,number,integer}.",
     arguments);

 output: At 12:30 PM on Jul 3, 2053, there was a disturbance
           in the Force on planet 7.

占位符的格式为{ ArgumentIndex , FormatType , FormatStyle },详细说明可以参考MessageFormat的API说明文档。这里我们定义了两个占位符,其中的数字对应于传入的参数数组中的索引,{0}占位符被第一个参数替换,{1}占位符被第二个参数替换,依此类推。
最多可以设置10个占位符,而且每个占位符可以重复出现多次,而且格式可以不同,比如{1,date}和{1,time},{1,number,#.##}。而通过将这些模式定义放到不同的资源文件中,就能够根据不同的locale设置,得到不同的模式定义,并用参数动态替换占位符。

步骤:
1、找出可变的部分,并据此定义模式,将模式放入不同的资源文件中。
2、创建MessageFormat对象,并设置其locale属性。


      MessageFormat formatter = new MessageFormat(""); 
      formatter.setLocale(currentLocale);

3、从资源包中得到模式定义,以及设置参数。


messages =     ResourceBundle.getBundle( 
  "i18n.resource.MessagesBundle",currentLocale); 
Object[] arguments= {new Long(3), "MyDisk"};;

4、利用模式定义和参数进行格式化。
        String result = MessageFormat.format(messages.getString(key), arguments);

猜你喜欢

转载自blog.csdn.net/candyguy242/article/details/80782250