为什么引入MessageFormat:
字符串类处理的缺点是字符串是不可变的对象,在堆内存中创建了更多的对象, 而且这些消息的顺序对每一种语言都不一样,因为这个问题, Sun引入了文本格式类,如MessageFormat。
String stringText="Hi"+ name+ "How are u";
MessageFormat是java.text包中的一个类,在java 5语言中引入,这个文本格式类在java中用于提供内部化的能力。
java.util.MessageFormat类提供了显示本地化特定消息的功能,并根据语言的不同对消息进行格式化。在任何应用程序中,当验证失败或请求成功提交时,消息会显示给用户。在现实世界的程序中,消息存储在资源包或属性文件中,程序根据语言读取属性文件。
MessageFormat的基本例子或用法
Object userInformation={"John","success"};
String messageText=" user {username} data is submitted with {status} message";
MessageFormat messageFormatExample=new MessageFormat(messageText);
System.out.println(messageFormatExample.format(userInformation));
and output is user John data is submitted with success message
在上面的代码中,format()方法通过接收{0},{1}参数来格式化字符串,MessageFormat很容易学习和实现。
如何格式化包含日期字段的文本信息
MessageFormat也可以处理包含日期和货币字段的信息,为此我们必须指定日期格式占位符,如下所示
Date currentDate = new Date();
Locale.setDefault(Locale.US);
System.out.println(MessageFormat.format("Current Date is {0,date yyyy-MM-dd}", date));
and output is Current Date is 2013-05-03
如何格式化包含数字字段的文本信息?
消息中的数字使用{0,number,000.000}的格式,显示带有3位小数的数字。
System.out.println(MessageFormat.format("Number is {0,number,000.000}", 123456));
and output is Number is 123.456