freeair
发贴: 88
积分: 50
|
于 2003-01-15 15:36
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 ); // becomes: MessageFormat formatter = new MessageFormat(message); String output = formatter.format(variables);
除了日期、时间、数字以及百分数之外,MessageFormat还可以处理货币值,使我们可以更灵活地控制数字的输出格式,同时它还允许指定ChoiceFormats。
MessageFormat是一个简洁的类,现在被使用的频率可能没有以前那么高。因为其最大缺点是输出的数据要以变量传入,而不能使用Properties对象。一个简单的解决方法是根据Properties.keys()返回的顺序值将Properties转换成一个数组下标从而将其包装(wrapper)成格式化的字符串。
|