Formatter class
First, let's look at the new java.util.Formatter
class. You probably won't use this class directly much, but it
provides the guts for the formatting you'll be doing. In the Javadoc
for this class, you'll find a table describing the supported
formatting options. These options range from something like %7.4f
for specifying the precision and width of a floating point number
to %tT for formatting a time to %3$s
for formatting the third argument.
Using Formatter to format output involves two
steps: creating an Appendable object to store
the output and using the format() method to put
formatted content into that object. Here's a list of implementers for the Appendable interface:
BufferedWriterCharArrayWriterCharBufferFileWriterFilterWriterLogStreamOutputStreamWriterPipedWriterPrintStreamPrintWriterStringBufferStringBuilderStringWriterWriter
An object implementing this interface can be used as the destination when
using a Formatter class by passing the object into the
Formatter constructor. Most of these classes should look
familiar, except for the StringBuilder class.
StringBuilder is nearly identical to the
StringBuffer class, with one big exception: It isn't
thread safe. If you know you are going to build up a string in a
single thread, use StringBuilder. If the building
can cross thread bounds, use StringBuffer. Listing 1 shows how you'd typically start using Formatter:
|
After creating a Formatter class, you call its
format() method with format strings and arguments.
If you need to use a different Locale than that
sent into the constructor for part of the formatted output, you can
also pass in a Locale object to the format()
method. Listing 2 shows the two varieties of format():
|
If you want to get the value of Pi to 10 digits of precision, the code in Listing 3
will put that value into the StringBuilder and print
the output. Printing the formatter object will display the
content of the Appendable object.
|
Don't forget to compile with the -source 1.5
option or the compiler won't recognize the variable argument
list. Because formatting output and sending it to the console are
common tasks, there are conveniences available to this behavior. We'll look at those next.
View Taming Tiger: Formatted output Discussion
Page: 1 2 3 4 5 Next Page: PrintStream support