摘自http://www.chinaitpower.com/A200507/2005-07-24/165741.html 本文是为ZDNet翻译的系列文章之一,原文已经发表在ZDNet网站Printf 是很多C语言程序员喜欢的工具,当他们转而使用Java时他们非常的失望。Java有一个替代的方法但是那个方法和C语言的printf() 函数的原理不一样。 幸运的是,早期的Java库的开发者认识到创建一个更合适Java的工具而不是一个printf 函数。 java.text.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 java.util.Date(), new Double(0.21) };String output = java.text.MessageFormat.format(message, variables);System.out.println(output); 隐藏在信息中的是描述输出的格式的一种短小的代码,范例的输出如下: Once upon a time (2008-7-19, around about 下午8:06), 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( )返回的顺序。

评论