主要介绍了:
![](https://images2015.cnblogs.com/blog/731047/201612/731047-20161201172345349-1880030166.png)
![](https://images2015.cnblogs.com/blog/731047/201612/731047-20161201172346677-602898172.png)
示例程序
运行结果
- 消息格式化的基本使用;
- 格式化:匹配数字;
- 格式化:匹配日期;
- 格式化:匹配时间;
- 格式化:多次匹配;
MessageFormat用来格式化一个消息,通常是一个字符串。MessageFormat模式的主要部分:
![](https://images2015.cnblogs.com/blog/731047/201612/731047-20161201172345349-1880030166.png)
下面是详细配置:
![](https://images2015.cnblogs.com/blog/731047/201612/731047-20161201172346677-602898172.png)
示例程序
package com.sssppp.Format;
import java.text.MessageFormat;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
public class MessageFormatExample {
public static void main(String[] args) {
// 基本匹配
String message = "基本匹配:{0}{1}{2}{3}{4}{5}{6}{7}{8}{9}{10}{11}{12}{13}{14}{15}{16}";
Object[] array = new Object[] { "A", "B", "C", "D", "E", "F", "G", "H",
"I", "J", "K", "L", "M", "N", "O", "P", "Q" };
String value = MessageFormat.format(message, array);
System.out.println(value); // ABCDEFGHIJKLMNOPQ
String message1 = "基本匹配:{0} is a person";
Object[] array1 = new Object[] { "ZhangSan" };
String value1 = MessageFormat.format(message1, array1);
System.out.println(value1); // oh, ZhangSan is a person
System.out.println();
// 数字匹配
System.out.println("数字匹配,匹配:3.1415");
List<String> numList = Arrays.asList("integer", "currency", "percent",
"#.##", "00.##");
for (String string : numList) {
String message2 = "{0,number," + string + "}";
Object[] array2 = new Object[] { new Double(3.1415) };
String value2 = MessageFormat.format(message2, array2);
System.out.println(value2);
}
System.out.println();
// 日期匹配
System.out.println("日期匹配");
List<String> dateList = Arrays.asList("yyyyMMdd-HH:mm:ss", "short",
"medium", "long", "full");
for (String string : dateList) {
String message3 = "{0,date," + string + "}";
String value3 = MessageFormat.format(message3, new Date());
System.out.println(value3);
}
System.out.println();
// 时间匹配
System.out.println("时间匹配");
List<String> timeList = Arrays.asList("yyyyMMdd-HH:mm:ss", "short",
"medium", "long", "full");
for (String string : timeList) {
String message4 = "{0,time," + string + "}";
String value4 = MessageFormat.format(message4, new Date());
System.out.println(value4);
}
System.out.println();
// 多次匹配
String message8 = "多次匹配:{0} | {1} | {0} | {1}";
Object[] array8 = new Object[] { "A", "B" };
String value8 = MessageFormat.format(message8, array8);
System.out.println(value8); // A | B | A | B
}
}
运行结果
基本匹配:ABCDEFGHIJKLMNOPQ
基本匹配:ZhangSan is a person
数字匹配,匹配:3.1415
3
¥3.14
314%
3.14
03.14
日期匹配
20161201-17:13:05
16-12-1
2016-12-1
2016年12月1日
2016年12月1日 星期四
时间匹配
20161201-17:13:05
下午5:13
17:13:05
下午05时13分05秒
下午05时13分05秒 CST
多次匹配:A | B | A | B
转载请标明出处:http://www.cnblogs.com/ssslinppp/