ThefmtSringconsists of two types of items. The first type is composed of characters that are
simply copied to the output buffer. The second type containsformat specifiersthat define the
way the subsequent arguments are displayed.
In its simplest form, a format specifier begins with a percent sign followed by the format
conversion specifier.All format conversion specifiers consist of a single character. For example,
the format specifier for floating-point data is%f. In general, there must be the same number
of arguments as there are format specifiers, and the format specifiers and the arguments are
matched in order from left to right. For example, consider this fragment:
Formatter fmt = new Formatter();
fmt.format("Formatting %s is easy %d %f", "with Java", 10, 98.6);
This sequence creates aFormatterthat contains the following string:
Formatting with Java is easy 10 98.600000
In this example, the format specifiers,%s,%d, and%f, are replaced with the arguments that
follow the format string. Thus,%sis replaced by “with Java”,%dis replaced by 10, and%f
is replaced by 98.6. All other characters are simply used as-is. As you might guess, the
format specifier%sspecifies a string, and%dspecifies an integer value. As mentioned
earlier, the%fspecifies a floating-point value.
Chapter 18: java.util Part 2: More Utility Classes 527
Method Description
void close( ) Closes the invokingFormatter. This causes any resources
used by the object to be released. After aFormatterhas
been closed, it cannot be reused. An attempt to use a
closedFormatterresults in aFormatterClosedException.
void flush( ) Flushes the format buffer. This causes any output currently
in the buffer to be written to the destination. This applies
mostly to aFormattertied to a file.
Formatter format(StringfmtString,
Object ...args)
Formats the arguments passed viaargsaccording to the format
specifiers contained infmtString.Returns the invoking object.
Formatter format(Localeloc,
StringfmtString,
Object ...args)
Formats the arguments passed viaargsaccording to the format
specifiers contained infmtString.The locale specified bylocis
used for this format. Returns the invoking object.
IOException ioException( ) If theunderlying object that is the destination for output throws
anIOException, then this exception is returned. Other wise,
null is returned.
Locale locale( ) Returns the invoking object’s locale.
Appendable out( ) Returns a reference to the underlying object that is the
destination for output.
String toString( ) Returns aStringcontaining the formatted output.
TABLE 18-11 The Methods Defined byFormatter