Java 5.0 | closeable flushable |
The Formatter class
is a utility for formatting text in the style of the printf(
) method of the C programming language. Every
Formatter has an associated
java.lang.Appendable object (such as a
StringBuilder or PrintWriter)
that is specified when the Formatter is created.
format( ) is a varargs method that expects a
"format string" argument followed
by some number of Object arguments. The format
string uses a grammar, described in detail later in the entry, to
specify how the arguments that follow are to be converted to strings.
After the arguments are converted, they are substituted into the
format string, and the resulting text is appended to the
Appendable. A variant of the format(
) method accepts a Locale object that
can affect the argument conversions.
For ease of use, a Formatter never throws a
java.io.IOException, even when the underlying
Appendable tHRows one. When using a
Formatter with a stream-based
Appendable object that may throw an
IOException, you can use the ioException(
) method to obtain the most recently thrown exception, or
null if no exception has been thrown by the
Appendable.
Formatter implements the
Closeable and Flushable
interfaces of the java.io package, and its
close( ) and flush( ) methods
call the corresponding methods on its Appendable
object, if that object itself implements Closeable
or Flushable. When a Formatter
sends its output to a stream or similar
Appendable, remember to call close(
) when you are done with it. It is always safe to call
close( ) even if the underlying
Appendable is not Closeable.
Note that once a Formatter has been closed, no
other method except ioException( ) may be called.
locale( ) returns the Locale
passed to the Formatter( ) constructor or
null. out( ) returns the
Appendable that this Formatter
sends its output to. toString( ) returns the
result of calling toString( ) on that
Appendable. This is useful when the
Appendable is a StringBuilder,
for example, as it is when the no-argument version of the
Formatter( ) constructor is used. If the
Appendable is a stream class, however, the
toString( ) method is not typically useful.
Note that the Java 5.0 API provides a number of convenience methods
that use the Formatter class, and in many cases it
is unnecessary to create a Formatter object
explicitly. See the static String.format( ) method
and the format( ) and printf( )
methods of java.io.PrintWriter and
java.io.PrintStream.
If you do need to create a Formatter object
explicitly, you can choose from a number of constructors. The most
general case is to pass the desired Appendable or
the desired Locale and
Appendable objects to the constructor. The
no-argument constructor is a convenience that creates a
StringBuilder to append to. Obtain this
StringBuilder with out( ) or
obtain its contents as a String with
toString( ). If you specify a single
Locale argument, the resulting
Formatter uses the specified locale with a
StringBuilder.
You can use a Formatter to write formatted output
to a file by specifying either the File object or
filename as a String. Variants of these
constructors allow you to specify the name of the charset to use for
character-to-byte conversion and also a Locale.
Note that these methods overwrite existing files rather than
appending to them. Other constructors create an
Appendable object for you based on the
java.io.OutputStream or
java.io.PrintStream you specify. In the
OutputStream case, you may optionally specify the
charset to use or the charset and a Locale.
The Format String and Format Specifiers
The API for
Formatter and Formatter-based
convenience methods is relatively
simple. The power of these formatting methods lies in the format
string that is the first argument (or second argument if a
Locale is specified) to the various
format( ) and printf( )
methods. The format string may contain any amount of regular text,
which is printed or appended literally to the destination
Appendable object. This plain text may be
interspersed with format
specifiers which specify how a subsequent
argument is to be formatted as a string. In contrast to the simple
API, the grammar for these format specifiers is surprisingly complex.
Experienced C programmers will find that the grammar is largely
compatible with the printf( ) format string
grammar of the standard C library.
Each format specifier begins with a percent sign and ends with a one-
or two-character conversion type that specifies most of the details
of the conversion and formatting. In between these two are optional
flags that provide additional details about how the formatting should
be done. The general syntax of a format specifier is as follows.
Square brackets indicate optional items:
%[argument][flags][width][.precision]type
Note that the percent sign and the type
are the only two required portions of a format specifier. We begin,
therefore, with a listing of conversion types (see Table 16-1). A discussion of
argument,
flags, width,
and precision follows. In the table of
conversion types below, if uppercase and lowercase variants of the
type specifier are listed together, the uppercase variant produces
the same output as the lowercase variant except that all lowercase
letters are converted to uppercase. Note that format(
) never throws NullPointerException
because of null arguments following the format
string. A null argument is formatted as
"null" or
"NULL" for all conversion
characters except %b and %B,
which produce "false" or
"FALSE".
Table 16-1. Formatter conversion types
Conversion
|
Description
|
---|
Simple conversions
|
%%
|
Outputs a single percent sign.This is simply an escape sequence used
to embed percent signs literally in the output string. This
conversion does not use an argument.
|
%n
|
Outputs the platform-specific line separator. This conversion
represents the value returned by
System.getProperty("line.separator").
This conversion does not use an argument.
|
%s, %S
|
Formats and outputs the argument as a string, optionally converting
it to uppercase for the %S conversion. The
argument may be of any type. If the argument implements
Formattable, its formatTo( )
method is called to perform the formatting. Otherwise, its
toString( ) method is called to convert it to a
string. If the argument is null, the output string
is "null" or
"NULL".
|
%c, %C
|
Outputs the argument as a single character. The argument type must be
Byte, Short,
Character, or Integer. The
argument value must represent a valid Unicode code point. (See
Character.isValidCodePoint( ).)
|
%b, %B
|
Outputs the argument value as the string
"true" or
"false" (or
"TRUE" or
"FALSE"). The argument may be of
any type and any value. If it is a Boolean
argument, the output reflects the argument value. Otherwise, if the
argument is null, the output is
"false" or
"FALSE". For any other value, the
output is "true" or
"TRUE". Note that this differs from
normal Java conversions in which boolean values
are not convertible to or from any other type.
|
%h, %H
|
Outputs the hexadecimal representation of the hashcode for the
argument. Arguments of any type and value are allowed. This
conversion type is useful mainly for debugging.
|
Numeric Conversions
|
%d
|
Formats the argument as a base-10 integer. The argument must be a
Byte, Short,
Integer, Long, or
BigInteger.
|
%o
|
Formats the argument as a base-8 octal integer. The allowed argument
types are the same as for %d. For any argument
type other than BigInteger, the value is treated
as unsigned.
|
%x, %X
|
Formats the argument as a base-16 hexadecimal integer. The allowed
argument types and values are the same as for %d.
For any argument type other than BigInteger, the
value is treated as unsigned.
|
%e, %E
|
Formats the argument as a base-10 floating-point number, using
exponential notation. The output consists of a single digit, a
locale-specific decimal point, and the number of fractional digits
specified by the precision of the format
specifier, or six fractional digits if no
precision is specified. These digits are
followed by the letter e or E
and the exponent of the number.
The argument must be a Float,
Double, or BigDecimal. The
values NaN and Infinity are
formatted as "NaN" and
"Infinity" or their uppercase
equivalents.
|
%f
|
Formats the argument as a floating-point number in base-10, without
using exponential notation. If the number is large, this may produce
quite a few digits. Because exponential notation is never used, the
output will never include a letter, and there is no uppercase variant
of this conversion. Legal argument types and special-case values are
as for %e.
|
%g, %G
|
Formats the argument as a base-10 floating-point number, displaying
no more than the number of significant digits specified by the
precision of the format specifier, or no
more than 6 significant digits if no
precision is specified. If the value has
more than the allowed number of significant digits, it is printed
using exponential notation (see %e) to limit the
display to the specified number of digits. Otherwise, all digits of
the value are printed explicitly as they would be with the
%f conversion type. Legal argument types and
special case values are as for %e.
|
%a, %A
|
Formats the argument in hexadecimal floating-point format. Legal
argument types and special case values are as for
%e.
|
Dates and Times
|
%t, %T
|
All date and time format types are two-letter codes beginning with
%t or %T. The specific format
types are listed below, in alphabetical order, using
%t as the prefix. For uppercase, use
%T instead. Upper- and lowercase variants of the
second letter of a time or date format type are sometimes completely
unrelated. Other times, the lowercase conversion produces an
abbreviation of the value produced by the uppercase conversion.
The argument for a date or time conversion must be a
Date, Calendar, or
Long. In the case of Long, the
value is interpreted as milliseconds since the epoch, as in
System currentTimeMillis( ).
|
%tA
|
The locale-specific full name of the day of the week.
|
%ta
|
The locale-specific abbreviation of the day of the week.
|
%tB
|
The locale-specific name of the month. See %tm.
|
%tb
|
The locale-specific abbreviation for the month.
|
%tC
|
The century: the year divided by 100, with leading zeros if necessary
to produce a value from 00 to 99
|
%tc
|
The complete date and time. Equivalent to "%ta %tb
%td %tT %tZ %tY".
|
%td
|
The date in a short numeric form used in the US locale. Equivalent to
"%tm/%td/%ty".
|
%td
|
The day of the month, as a two-digit number between 01 and 31. See
%te.
|
%tE
|
The date expressed as milliseconds since Midnight UTC on January 1st,
1970.
|
%te
|
The day of the month as a one- or two-digit number without leading
zeros between 1 and 31. See %td.
|
%tF
|
The numeric date in ISO8601 format: %tY-%tm-%td.
|
%tH
|
Hour of the day using a 24-hour clock, formatted as two digits
between 00 and 23. See %tI.
|
%th
|
The abbreviated month name. Same as %tb.
|
%tI
|
Hour of the day using a 12-hour clock, formatted as two digits
between 01 and 12. See %tH and
%tP.
|
%tj
|
The day of the year as three digits with leading zeros if necessary:
001-366
|
%tk
|
Hour of the day on a 24-hour clock using one or two digits without a
leading zero: 0-23. See %tl.
|
%tL
|
Milliseconds within the second, expressed as three digits with
leading zeros: 000-999.
|
%tl
|
Hour of the day on a 12-hour clock using one or two digits without a
leading zero: 1-12.
|
%tM
|
Minute within the hour as two digits with a leading zero if
necessary: 00-59.
|
%tm
|
The month of the year as a two-digit number between 01 and 12, or
between 01 and 13 for lunar calendars. See %tB and
%tb.
|
%tN
|
Nanosecond within the second, expressed as nine digits with leading
zeros if necessary. Note that platforms are not required to able to
resolve times with nanosecond precision.
|
%tP
|
The locale-specific morning or afternoon indicator (such as
"am" or
"pm") used with 12-hour clocks.
%tP uses lowercase and %TP uses
uppercase.
|
%tp
|
Like %tP but uses uppercase for both
%tp and %Tp variants.
|
%tr
|
The hour and minute on a 24-hour clock. Equivalent to
"%tH:%tM".
|
%tr
|
The hour, minute, and second on a 12-hour clock. Equivalent to
"%tI:%tM:%tS %tP" except that the
am/pm indicator %tP may be in a different
locale-dependent position.
|
%tS
|
Seconds within the minute, as two digits with a leading zero if
necessary. The range is normally 00-59, but a value of 60 is allowed
for leap seconds.
|
%ts
|
Seconds since the beginning of the epoch. See %tE.
|
%tT
|
The time in hours, minutes, and seconds using 24-hour format.
Equivalent to "%tH:%tM:%tS".
|
%tY
|
The year, using at least four digits, formatted with leading zeros,
if necessary.
|
%ty
|
The last two digits of the year, 00-99
|
%tZ
|
An abbreviation for the time zone.
|
%tz
|
The time zone as numeric offset from GMT.
|
Argument Specifier
Every format specifier in a format string
except for %% and %n requires
an argument that contains the value to format. These arguments follow
the format string in the call to format( ) or
printf( ). By default, a format specifier uses the
next unused argument. In the following printf( )
call, the first and second %s format specifiers
format the second and third arguments, respectively:
out.printf("Name: %s %s%n", first, last);
If a format specifier includes the character <
after the %, it specifies that the argument of the
previous format specifier should be reused. This allows the same
object (such as a date) to be formatted more than once (yielding a
formatted date and time, for example):
out.printf("Date: %tD%nTime: %<tr%n", System.currentTimeMillis( ));
It is an error to use < in the first format
specifier of a format string.
Argument numbers may also be specified absolutely. If the
% sign is followed by one or more digits and a
$ sign, those digits specify an argument number.
For example %1$d specifies that the first argument
following the format string should be formatted as an integer.
Absolute argument numbers are particularly useful for localization
since the different translations of a message may need to interpolate
the arguments in a different order. The following example includes a
format string that might be used in a locale where a
person's family name is typically printed (in
uppercase) before the given name. Note that the arguments are not
passed in the same order that they are formatted.
String name = String.format("%2$S, %1$s", firstname, lastname);
Neither absolute argument indexing with a number and
$ character or relative argument indexing with
< affect the order in which arguments are
interpolated for format specifiers that use neither
$ or <. The first format
specifier that has neither an absolute or relative argument
specification uses the first argument following the format string,
regardless of what has come before. The code above could be rewritten
like this, for example:
String name = String.format("%2$S, %s", firstname, lastname);
Flags
Following the
optional argument specifier, a format specifier may include one or
more flag characters. The defined flags, their effects, and the
format types for which they are legal are specified in Table 16-2:
Table 16-2. Formatter flags
Flag
|
Description
|
---|
-
|
A hyphen specifies that the formatted value should be left-justified
within the specified width. This flag can
be used with any conversion type except %n as long
as the conversion specifier also includes a
width (see below). When a width is
specified without this flag, the formatted string is padded on the
left to produce right-justified output.
|
#
|
The # flag specifies that output should appear in
an "alternate form" that depends on
the type being formatted. For %o conversions, this
flag specifies that the output should include a leading 0. For
%x and %X conversions, it
specifies that output should include a leading 0x
or 0X. For the %s and
%S conversions, the # flag may
be used if the argument implements Formattable. In
this case, the flag is passed on to the formatTo(
) method of the argument, and it is up to that
formatTo( ) method to produce its output in some
alternate form.
|
+
|
This flag specifies that numeric output should always include a sign:
a value that is nonnegative will have
"+" added in front of it. This flag
may be used with any numeric conversion that may yield a signed
result. This includes %d, %e,
%f, %g, %a,
and their uppercase variants. It also includes %o,
%x, and %X conversions applied
to BigInteger arguments.
| |
The space character is a (hard-to-read) flag that specifies that
non-negative values should be prefixed with a space. This flag may be
used with the same conversion and argument types as the
+ flag, and is useful when aligning positive and
negative numbers in a column
|
(
|
This flag specifies that negative numbers should be enclosed in
parentheses, as is commonly done in financial statements, for
example. This flag may be used with the same format and argument
types as the + flag, except that it may not be
used with %a conversions.
|
0
|
The digit zero, used as a flag, specifies that numeric values should
be padded on the left (after the sign character, if any) with zeros.
This flag may be used only if a width is specified, and may not be
used in conjunction with the - flag.
|
,
|
This flag specifies that numbers should be formatted using the
locale-specific grouping separator. In the US locale, for example, a
comma would appear every three digits to separate the number into
thousands, millions, and so on. This flag may be used with
%d, %e, %E,
%f, %g, and
%G conversions only.
|
Width
The width portion of a format specifier is
one or more digits that specify the minimum number of characters to
be produced. If the formatted value is narrower than the specified
width, (by default) it is padded on the left with spaces, producing a
right-justified value. The - and
0 flags can be used to specify left-justification
or padding with zeros instead.
A width may be specified with any format type except
%n.
Precision
The precision
portion of a format
specifier is one or more digits following a decimal point. The
meaning of this number depends on which format type it is used with:
For %e, %E, and
%f, the precision specifies the number of digits
to appear after the decimal point. Zeros are appended on the right,
if necessary. The default precision is 6. For %g and %G format types, the
precision specifies the total number of significant digits to be
displayed. As a corollary, it specifies the largest and smallest
values that can be displayed without resorting to exponential
notation. The default precision is 6. If a precision of 0 is
specified, it is treated as a precision of 1. For %s, %h and
%b format types, and their uppercase variants, the
precision specifies the maximum number of characters to be output. If
no precision is specified, there is no maximum. If the formatted
output would exceed the precision of
characters, it is truncated. If precision
is smaller than width, the formatted value
is first truncated as necessary and then padded within the specified
width. Specifying a precision for any other conversion type causes an
exception at runtime.
Synopsis

public final class Formatter implements java.io.Closeable, java.io.Flushable {
// Public Constructors
public Formatter( );
public Formatter(java.io.PrintStream ps);
public Formatter(java.io.OutputStream os);
public Formatter(java.io.File file) throws java.io.FileNotFoundException;
public Formatter(String fileName) throws java.io.FileNotFoundException;
public Formatter(Locale l);
public Formatter(Appendable a);
public Formatter(java.io.OutputStream os, String csn)
throws java.io.UnsupportedEncodingException;
public Formatter(java.io.File file, String csn)
throws java.io.FileNotFoundException, java.io.UnsupportedEncodingException;
public Formatter(Appendable a, Locale l);
public Formatter(String fileName, String csn)
throws java.io.FileNotFoundException, java.io.UnsupportedEncodingException;
public Formatter(String fileName, String csn, Locale l)
throws java.io.FileNotFoundException, java.io.UnsupportedEncodingException;
public Formatter(java.io.File file, String csn, Locale l)
throws java.io.FileNotFoundException, java.io.UnsupportedEncodingException;
public Formatter(java.io.OutputStream os, String csn, Locale l)
throws java.io.UnsupportedEncodingException;
// Nested Types
public enum BigDecimalLayoutForm;
// Public Instance Methods
public java.util.Formatter format(String format, Object... args);
public java.util.Formatter format(Locale l, String format, Object... args);
public java.io.IOException ioException( );
public Locale locale( );
public Appendable out( );
// Methods Implementing Closeable
public void close( );
// Methods Implementing Flushable
public void flush( );
// Public Methods Overriding Object
public String toString( );
}
Passed To
Formattable.formatTo( )
|