Java The Complete Reference, Seventh Edition

(Greg DeLong) #1

526 Part II: The Java Library


The Formatter Constructors


Before you can useFormatterto format output, you must create aFormatterobject. In general,
Formatterworks by converting the binary form of data used by a program into formatted
text. It stores the formatted text in a buffer, the contents of which can be obtained by your
program whenever they are needed. It is possible to letFormattersupply this buffer
automatically, or you can specify the buffer explicitly when aFormatterobject is created.
It is also possible to haveFormatteroutput its buffer to a file.
TheFormatterclass defines many constructors, which enable you to construct aFormatter
in a variety of ways. Here is a sampling:

Formatter( )

Formatter(Appendablebuf)

Formatter(Appendablebuf, Localeloc)

Formatter(Stringfilename)
throws FileNotFoundException

Formatter(Stringfilename, Stringcharset)
throws FileNotFoundException, UnsupportedEncodingException

Formatter(FileoutF)
throws FileNotFoundException

Formatter(OutputStreamoutStrm)

Here,bufspecifies a buffer for the formatted output. Ifbufis null, thenFormatterautomatically
allocates aStringBuilderto hold the formatted output. Thelocparameter specifies a locale.
If no locale is specified, the default locale is used. Thefilenameparameter specifies the name
of a file that will receive the formatted output. Thecharsetparameter specifies the character
set. If no character set is specified, then the default character set is used. TheoutFparameter
specifies a reference to an open file that will receive output. TheoutStrmparameter specifies
a reference to an output stream that will receive output. When using a file, output is also
written to the file.
Perhaps the most widely used constructor is the first, which has no parameters.
It automatically uses the default locale and allocates aStringBuilderto hold the formatted
output.

The Formatter Methods


Formatterdefines the methods shown in Table 18-11.

Formatting Basics


After you have created aFormatter, you can use it to create a formatted string. To do so, use
theformat( )method. The most commonly used version is shown here:

Formatter format(StringfmtString, Object ...args)
Free download pdf