使用MessageFormat控制输出

王朝other·作者佚名  2008-05-31
窄屏简体版  字體: |||超大  

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( )返回的顺序。

 
 
 
免责声明:本文为网络用户发布,其观点仅代表作者个人观点,与本站无关,本站仅提供信息存储服务。文中陈述内容未经本站证实,其真实性、完整性、及时性本站不作任何保证或承诺,请读者仅作参考,并请自行核实相关内容。
 
 
© 2005- 王朝網路 版權所有 導航