printf是很多c语言程序员喜欢的工具,当他们转而使用java时他们非常的失望。java有一个替代的方法但是那个方法和c语言的printf() 函数的原理不一样。
幸运的是,早期的java库的开发者认识到创建一个更合适java的工具而不是一个printf函数。
messageformat运行开发者输出文本中的变量的格式。它是一个强大的类,就像下面的例子展示的那样:
string message =
"once upon a time ({1,date}, around about {1,time,short}), there " +
"was a humble developer named geppetto who slaved for " +
"{0,number,integer} days with {2,number,percent} complete user " +
"requirements. ";
object[ ] variables = new object[ ]
{ new integer(4), new date( ), new double(0.21) }
string output = messageformat.format( message, variables );
system.out.println(output);
隐藏在信息中的是描述输出的格式的一种短小的代码,范例的输出如下:
once upon a time (nov 3, 2002, around about 1:35 am), there was a humble developer
named geppetto who slaved for 4 days with 21% complete user requirements.
如果相同的信息需要被重复输出但是变量的值不同,那么创建一个messageformat对象并给出信息。下面是上面的例子的修正版:
//string output = messageformat.format(message, variables );
//变为:
messageformat formatter = new messageformat(message);
string output = formatter.format(variables);
除了可以处理日期、时间、数字和百分数外,messageformat也可以处理货币,运行更多的数字格式的控制并且允许指定choiceformat。
messageformat是一个极好的类,它应该经常被使用但是现在还没有。它的最大的缺点是数据是被作为变量传递而不是一个properties对象。一个简单的解决办法是写一个封装类,它会预解析字符串为格式化的结果,将properties的key转换为一个数组索引,顺序是properties.keys( )返回的顺序。
闽公网安备 35060202000074号