Java开发网 Java开发网
注册 | 登录 | 帮助 | 搜索 | 排行榜 | 发帖统计  

您没有登录

» Java开发网 » 技术文章库  

按打印兼容模式打印这个话题 打印话题    把这个话题寄给朋友 寄给朋友    该主题的所有更新都将Email到你的邮箱 订阅主题
flat modethreaded modego to previous topicgo to next topicgo to back
作者 [转贴]使用MessageFormat控制输出 转自ZDNet China
freeair





发贴: 88
积分: 50
于 2003-01-15 15:36 user profilesend a private message to usersearch all posts byselect and copy to clipboard. 
ie only, sorry for netscape users:-)add this post to my favorite list
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)成格式化的字符串。




话题树型展开
人气 标题 作者 字数 发贴时间
7257 [转贴]使用MessageFormat控制输出 转自ZDNet China freeair 1322 2003-01-15 15:36

flat modethreaded modego to previous topicgo to next topicgo to back
  已读帖子
  新的帖子
  被删除的帖子
Jump to the top of page

   Powered by Jute Powerful Forum® Version Jute 1.5.6 Ent
Copyright © 2002-2021 Cjsdn Team. All Righits Reserved. 闽ICP备05005120号-1
客服电话 18559299278    客服信箱 714923@qq.com    客服QQ 714923