`
soboer
  • 浏览: 1312608 次
文章分类
社区版块
存档分类
最新评论

MessageFormat(动态文本)

 
阅读更多

MessageFormat(动态问文本)

一.如果一个字符串中包含了多个与国际化相关的数据,可以使用MessageFormat类对这些数据进行批量处理。

例如:At 12:30 pm on jul 3,1998, a hurricance destroyed 99 houses and caused $1000000 of damage

• 以上字符串中包含了时间、数字、货币等多个与国际化相关的数据,对于这种字符串,可以使用MessageFormat类对其国际化相关的数据进行批量处理。

MessageFormat 类如何进行批量处理呢?

• MessageFormat类允许开发人员用占位符替换掉字符串中的敏感数据(即国际化相关的数据)。

• MessageFormat类在格式化输出包含占位符的文本时,messageFormat类可以接收一个参数数组,以替换文本中的每一个占位符。

二. 模式字符串:

On {0}, a hurricance destroyed {1} houses and caused {2} of damage.

MessageFormat类

• MessageFormat(String pattern)

l 实例化MessageFormat对象,并装载相应的模式字符串。

• format(object obj[])

l 格式化输出模式字符串,参数数组中指定占位符相应的替换对象。

l format(new Object[ ]{date, new Integer(99), new Double(1E7) })

例题讲解:package com.hbsi.test;

import java.text.MessageFormat;

import java.util.Date;

import java.util.Locale;

import java.util.ResourceBundle;

public class Demo3 {

/**

* @param args

*/

public static void main(String[] args) {

// TODO Auto-generated method stub

//模式字符串

String pattern="At{0,time,full} on{0,date,long}, a hurricance destroyed {1,number} houses and caused {2,number,currency} of damage.";

MessageFormat mf=new MessageFormat(pattern,Locale.US);

//准备参数数组

Object [] objs={new Date(),new Integer(99),new Double(1e7)};

//执行格式化

String result=mf.format(objs);

System.out.println(result);

//加入到资源文件中

ResourceBundle bundle=ResourceBundle.getBundle("com.hbsi.resource.MyResource",Locale.ENGLISH);

result=bundle.getString("title");

//System.out.println(result);

MessageFormat mf1=new MessageFormat(result,Locale.ENGLISH);

System.out.println(mf.format(objs));

}

}

三.模式字符串与占位符

l 占位符有三种方式书写方式:

• {argumentIndex}: 0-9 之间的数字,表示要格式化对象数据在参数数组中的索引号

• {argumentIndex,formatType}: 参数的格式化类型

• {argumentIndex,formatType,FormatStyle}: 格式化的样式,它的值必须是与格式化类型相匹配的合法模式、或表示合法模式的字符串。

代码分析:

String pattern = "At {0, time, short} on {0, date}, a destroyed'\n'"

+ "{1} houses and caused {2, number, currency} of damage.";

MessageFormat msgFmt = new MessageFormat(pattern,Locale.US);

String datetimeString = "Jul 3, 1998 12:30 PM";

Date date = DateFormat.getDateTimeInstance(DateFormat.MEDIUM,

DateFormat.SHORT,Locale.US).parse(datetimeString);

String event = "a hurricance";

Object []msgArgs = {date, event, new Integer(99), new Double(1E7)};

String result = msgFmt.format(msgArgs);

System.out.println(result);

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics