目录
一、MessageFormat模式
二、用法
三、关于MessageFormat.format方法:
FormatElement
{ ArgumentIndex }:是从0开始的入参位置索引
{ ArgumentIndex , FormatType }
{ ArgumentIndex , FormatType , FormatStyle }
FormatType:指定使用不同的Format子类对入参进行格式化处理。值范围如下:
number:调用NumberFormat进行格式化
date:调用DateFormat进行格式化
time:调用DateFormat进行格式化
choice:调用ChoiceFormat进行格式化
FormatStyle:设置FormatType中使用的格式化样式。值范围如下:
short、medium、long、full、integer、currency、percent、SubformatPattern (子格式模式,形如#.##)
还以str为例,在这个字符串中:
1、{0}和{1,number,short}和{2,number,#.#};都属于FormatElement,0,1,2是ArgumentIndex。
2、{1,number,short}里面的number属于FormatType,short则属于FormatStyle。
3、{1,number,#.#}里面的#.#就属于子格式模式。
指定FormatType和FormatStyle是为了生成日期格式的值、不同精度的数字、百分比类型等等。
1、ArgumentIndex必须是非负整数,它的个数不只限于0到9这10个,它可以用0到9的数字组成,因此可以有好多个,如:
String msg = "{0}{1}{2}{3}{4}{5}{6}{7}{8}";
Object [] array = new Object[]{"A","B","C","D","E","F","G","H","I",};
String value = MessageFormat.format(msg, array);
System.out.println(value);// 输出:ABCDEFGHI
2、格式化字符串时,两个单引号才表示一个单引号,单个单引号会被省略,除非中文单引号不会被省略,如:
String value = MessageFormat.format("oh, {0} is 'a' pig", "ZhangSan");
System.out.println(value); // 输出:oh, ZhangSan is a pig
3、单引号会使其后面的占位符均失效,导致直接输出占位符:
String m1 = MessageFormat.format("{0}{1}",1, 2); // 结果12
String m2 = MessageFormat.format("'{0}{1}",1, 2); // 结果{0}{1}
String m3 = MessageFormat.format("'{0}'-{1}",1, 2); // 结果{0}-2
System.out.println(m1);
System.out.println(m2);
System.out.println(m3);
4、无论是有引号字符串还是无引号字符串,左花括号都是不支持的,如:
String value = MessageFormat.format("oh, } is good num", Double.valueOf("3.1415"));
System.out.println(value); // 输出:oh, } is good num
如果使用左花括号会出现异常
String value = MessageFormat.format("oh, { is good num", Double.valueOf("3.1415"));
System.out.println(value); // java.lang.IllegalArgumentException: Unmatched braces in the pattern.
因此要使用到左花括号需要使用单引号配合使用
MessageFormat.format("'{'{0}}", "X-rapido"); // {X-rapido}
每调用一次MessageFormat.format方法,都会新创建MessageFormat的一个实例,相当于MessageFormat只使用了一次。MessageFormat类的format方法如下:
public static String format(String pattern, Object ... arguments){
MessageFormat temp = new MessageFormat(pattern);
return temp.format(arguments);
}
因此若要多次格式同一个模式的字符串,那么创建一个MessageFormat实例在执行格式化操作比较好些
String message = "oh, {0} is a pig";
MessageFormat messageFormat = new MessageFormat(message);
Object[] array = new Object[]{"ZhangSan"};
String value = messageFormat.format(array);
System.out.println(value);