#####一:案例
String pattern = "ErrorMessage=This is Error Message : {0}.";
String returnStr = MessageFormat.format(pattern, "hello world");
System.out.println(returnStr);
#####二:java.text.MessageFormat.format静态方法
方法定义:
StringMessageFormat.format(Stringpattern, Object…args)
输入参数pattern为MessageFormat模式参数。
######MessageFormat模式
格式: {ArgumentIndex[,FormatType[,FormatStyle]]}
语法:真个表达式为一个字符串,需要替换的参数信息放在花括号{}中。
ArgumentIndex ,是从0开始的入参位置索引。
FormatType ,指定使用不同的Format子类对入参进行格式化处理。值范围如下:
number:调用NumberFormat进行格式化
date:调用DateFormat进行格式化
time:调用DateFormat进行格式化
choice:调用ChoiceFormat进行格式化
FormatStyle :
short
medium
long
full
integer
currency
percent
SubformPattern(子格式模式,形如#.##)
FormatType 和 FormatStyle 主要用于对日期时间、数字、百分比等进行格式化
String pattern1="this message :数字;{0,number,#.##}, 日期;{1,date}";
Date date = new Date();
Object[] objects={10.123,date,"晴朗"};
String returnStr1= MessageFormat.format(pattern1 , objects );
log.info(returnStr1);
输出: this message :数字;10.12, 日期;2018-9-4
####三、注意点:
-
两个单引号才表示一个单引号,仅写一个单引号将被忽略。
-
单引号会使其后面的占位符均失效,导致直接输出占位符。
-
如果传入多个参数,但实际需要替换的占位符没有那么多,程序并不会报错。
MessageFormat.format("{0}{1}", 1, 2); // 结果12
MessageFormat.format("'{0}{1}", 1, 2); // 结果{0}{1}
MessageFormat.format("'{0}'{1}", 1, 2); // 结果{0}2
MessageFormat.format("'{'{0}", 2); // 结果{2
MessageFormat.format("First:{0},Second:{1},third.", 1,2,3);
######参考:
https://blog.csdn.net/mahoking/article/details/52506285