我会考虑下载你对应的Java版本的Javadoc和源罐子,因为你所有的问题可以很容易地通过查看源文件来回答。
System.out.printf(formatString, args)
System.out
是PrintStream
。 PrintStream.printf(formatString, args)
实际上是一个方便的方法调用PrintStream.format(formatString, args);
。
System.out.format(formatString, args)
这是PrintStream.format(formatString, args)
调用它采用了Formatter
格式化结果并将其追加到PrintStream
。
String.format(formatString, args)
这种方法也使用了Formatter
并返回与格式字符串和args的格式化结果一个新的字符串。
System.console().format(formatString, args)
System.console()
是Console
。 Console.format(format, args)
使用Formatter
向控制台显示格式化的字符串。
new Formatter(new StringBuffer("Test")).format(formatString, args);
这将创建使用传递的字符串缓冲区Formatter
的一个实例。如果你使用这个电话,那么你将不得不使用out()
方法来获得由Formatter
写入Appendable
。相反,你可能想要做这样的事情:
StringBuffer sb = new StringBuffer("Test");
new Formatter(sb).format(formatString, args);
// now do something with sb.toString()
最后:
DecimalFormat.format(value);
NumberFormat.format(value);
这些是值的两种concreate格式化是做不使用Formatter
类。 DecimalFormat
和NumerFormat
都有一个format
方法,它采用双精度或者Number
,并根据这些类的定义将它们格式化为字符串。据我所知,Formatter
不使用它们。
希望这会有所帮助。
它们只是包装'Formatter'功能的简便方法。 (不知道'NumberFormat'及其子类是如何与之相关的,即关系是以哪种方式流动的。) – 2011-12-31 16:51:37
@Dave但是仍然是一个很好的问题,为什么我们有'PrintStream.format'和'PrintStream.printf' - afaik他们在同一版本中添加并具有相同的功能。用于printf偶数状态的jdocs:'调用out.printf(format,args)形式的此方法的行为与调用out.format(format,args)'的行为完全相同。奇怪的发布确实 – Voo 2011-12-31 17:12:55
@Voo我猜想有人添加了所有'printf'的东西来保持'format'功能更符合'print' /'println'等,但这只是一个猜测。大多数API都有一定量的重复,出于各种原因 - 允许不同的样式,以不同的方式表达意图等等。 – 2011-12-31 17:17:52