Class Formatter
- java.lang.Object
-
- java.util.Formatter
-
- All Implemented Interfaces:
Closeable,Flushable,AutoCloseable
public final class Formatter extends Object implements Closeable, Flushable
An interpreter for printf-style format strings. This class provides support for layout justification and alignment, common formats for numeric, and string output. Common Java types such asbyte, andIntegerare supported.Formatters are not necessarily safe for multithreaded access. Thread safety is optional and is the responsibility of users of methods in this class.
Formatted printing for the Java language is heavily inspired by C's
printf. Although the format strings are similar to C, some customizations have been made to accommodate the Java language and exploit some of its features. Also, Java formatting is more strict than C's; for example, if a conversion is incompatible with a flag, an exception will be thrown. In C inapplicable flags are silently ignored. The format strings are thus intended to be recognizable to C programmers but not necessarily completely compatible with those in C.Examples of expected usage:
StringBuilder sb = new StringBuilder(); // Send all output to the Appendable object sb Formatter formatter = new Formatter(sb, Locale.US); // Explicit argument indices may be used to re-order output. formatter.format("%4$2s %3$2s %2$2s %1$2s", "a", "b", "c", "d") // -> " d c b a" // The precision and width can be given to round and align the value. formatter.format("e = %+10.4f", Math.E); // -> "e = +2.7183" // The '(' numeric flag may be used to format negative numbers with // parentheses rather than a minus sign. Group separators are // automatically inserted. formatter.format("Amount gained or lost since last statement: $ %(,.2f", balanceDelta); // -> "Amount gained or lost since last statement: $ (6,217.58)"Convenience methods for common formatting requests exist as illustrated by the following invocations:
// Writes formatted output to System.err. System.err.printf("Unable to open file '%1$s': %2$s", fileName, exception.getMessage()); // -> "Unable to open file 'food': No such file or directory"Organization
This specification is divided into two sections. The first section, Summary, covers the basic formatting concepts. This section is intended for users who want to get started quickly and are familiar with formatted printing in other programming languages. The second section, Details, covers the specific implementation details. It is intended for users who want more precise specification of formatting behavior.
Summary
This section is intended to provide a brief overview of formatting concepts. For precise behavioral details, refer to the Details section.
Format String Syntax
Every method which produces formatted output requires a format string and an argument list. The format string is a
Stringwhich may contain fixed text and one or more embedded format specifiers. Consider the following example:
This format string is the first argument to theCalendar c = ...; String s = String.format("Hello %1$s", name);formatmethod. It contains one format specifier "%1$s" which indicate how the arguments should be processed and where they should be inserted in the text. The remaining portions of the format string are fixed text including"Hello "and any other spaces or punctuation. The argument list consists of all arguments passed to the method after the format string. In the above example, the argument list is of size one and consists of theStringobjectc.- The format specifiers for general, character, and numeric types have the following syntax:
%[argument_index$][flags][width][.precision]conversion
The optional argument_index is a decimal integer indicating the position of the argument in the argument list. The first argument is referenced by "
1$", the second by "2$", etc.The optional flags is a set of characters that modify the output format. The set of valid flags depends on the conversion.
The optional width is a positive decimal integer indicating the minimum number of characters to be written to the output.
The optional precision is a non-negative decimal integer usually used to restrict the number of characters. The specific behavior depends on the conversion.
The required conversion is a character indicating how the argument should be formatted. The set of valid conversions for a given argument depends on the argument's data type.
- The format specifiers which do not correspond to arguments have the following syntax:
%[flags][width]conversion
The optional flags and width is defined as above.
The required conversion is a character indicating content to be inserted in the output.
Conversions
Conversions are divided into the following categories:
- General - may be applied to any argument type
- Character - may be applied to basic types which represent Unicode characters:
char,Character. - Numeric
- Percent - produces a literal
'%'('\u0025') - Line Separator - produces the platform-specific line separator
The following table summarizes the supported conversions. Conversions denoted by an upper-case character (i.e.
'B','H','S','C', and'X') are the same as those for the corresponding lower-case conversion characters except that the result is converted to upper case. The result is equivalent to the following invocation ofString.toUpperCase()out.toUpperCase()
Conversion Argument Category Description 'b','B'general If the argument arg is null, then the result is "false". If arg is abooleanorBoolean, then the result is the string returned byString.valueOf(arg). Otherwise, the result is "true".'h','H'general If the argument arg is null, then the result is "null". Otherwise, the result is obtained by invokingInteger.toHexString(arg.hashCode()).'s','S'general If the argument arg is null, then the result is "null". The result is obtained by invokingarg.toString().'c','C'character The result is a Unicode character 'd'integral The result is formatted as a decimal integer 'o'integral The result is formatted as an octal integer 'x','X'integral The result is formatted as a hexadecimal integer 'f'floating point The result is formatted as a decimal number '%'percent The result is a literal '%'('\u0025')'n'line separator The result is the platform-specific line separator Any characters not explicitly defined as conversions are illegal and are reserved for future extensions.
Flags
The following table summarizes the supported flags. y means the flag is supported for the indicated argument types.
Flag General Character Integral Floating Point Description '-' y y y y The result will be left-justified. '#' y - y1 y The result should use a conversion-dependent alternate form '+' - - y2 y The result will always include a sign ' ' - - y2 y The result will include a leading space for positive values '0' - - y y The result will be zero-padded '(' - - y2 y3 The result will enclose negative numbers in parentheses 1 For
'o','x', and'X'conversions only.2 For
'd'conversions applied tobyte,Byte,short,Short,intandInteger,long, andLong.3 For
'f'conversion only.Any characters not explicitly defined as flags are illegal and are reserved for future extensions.
Width
The width is the minimum number of characters to be written to the output. For the line separator conversion, width is not applicable; if it is provided, an exception will be thrown.
Precision
For general argument types, the precision is the maximum number of characters to be written to the output.
For the floating-point conversion
'f'the precision is the number of digits after the radix point.For character, and integral argument types and the percent and line separator conversions, the precision is not applicable; if a precision is provided, an exception will be thrown.
Argument Index
The argument index is a decimal integer indicating the position of the argument in the argument list. The first argument is referenced by "
1$", the second by "2$", etc.Another way to reference arguments by position is to use the
'<'('\u003c') flag, which causes the argument for the previous format specifier to be re-used. For example, the following two statements would produce identical strings:Calendar c = ...; String s1 = String.format("Hello %1$s, how are you %1$s", name); String s2 = String.format("Hello %1$s, how are you %<$s", name);
Details
This section is intended to provide behavioral details for formatting, including conditions and exceptions, supported data types, localization, and interactions between flags, conversions, and data types. For an overview of formatting concepts, refer to the Summary
Any characters not explicitly defined as conversions, or flags are illegal and are reserved for future extensions. Use of such a character in a format string will cause an
UnknownFormatConversionExceptionorUnknownFormatFlagsExceptionto be thrown.If the format specifier contains a width or precision with an invalid value or which is otherwise unsupported, then a
IllegalFormatWidthExceptionorIllegalFormatPrecisionExceptionrespectively will be thrown.If a format specifier contains a conversion character that is not applicable to the corresponding argument, then an
IllegalFormatConversionExceptionwill be thrown.All specified exceptions may be thrown by any of the
formatmethods ofFormatter.Conversions denoted by an upper-case character (i.e.
'B','H','S','C', and'X') are the same as those for the corresponding lower-case conversion characters except that the result is converted to upper case. The result is equivalent to the following invocation ofString.toUpperCase()out.toUpperCase()
General
The following general conversions may be applied to any argument type:
'b''\u0062' Produces either " true" or "false" as returned byBoolean.toString(boolean).If the argument is
null, then the result is "false". If the argument is abooleanorBoolean, then the result is the string returned byString.valueOf(). Otherwise, the result is "true".If the
'#'flag is given, then aFormatFlagsConversionMismatchExceptionwill be thrown.'B''\u0042' The upper-case variant of 'b'.'h''\u0068' Produces a string representing the hash code value of the object. If the argument, arg is
null, then the result is "null". Otherwise, the result is obtained by invokingInteger.toHexString(arg.hashCode()).If the
'#'flag is given, then aFormatFlagsConversionMismatchExceptionwill be thrown.'H''\u0048' The upper-case variant of 'h'.'s''\u0073' Produces a string. If the argument is
null, then the result is "null". The result is obtained by invoking the argument'stoString()method.If the
'#'flag is given aFormatFlagsConversionMismatchExceptionwill be thrown.'S''\u0053' The upper-case variant of 's'.The following flags apply to general conversions:
'-''\u002d' Left justifies the output. Spaces ('\u0020') will be added at the end of the converted value as required to fill the minimum width of the field. If the width is not provided, then a MissingFormatWidthExceptionwill be thrown. If this flag is not given then the output will be right-justified.'#''\u0023' Requires the output use an alternate form. The definition of the form is specified by the conversion. The width is the minimum number of characters to be written to the output. If the length of the converted value is less than the width then the output will be padded by ' ' ( '\u0020') until the total number of characters equals the width. The padding is on the left by default. If the
'-'flag is given, then the padding will be on the right. If the width is not specified then there is no minimum.The precision is the maximum number of characters to be written to the output. The precision is applied before the width, thus the output will be truncated to
precisioncharacters even if the width is greater than the precision. If the precision is not specified then there is no explicit limit on the number of characters.Character
This conversion may be applied tocharandCharacter.'c''\u0063' Formats the argument as a Unicode character as described in Unicode Character Representation. This may be more than one 16-bit charin the case where the argument represents a supplementary character.If the
'#'flag is given, then aFormatFlagsConversionMismatchExceptionwill be thrown.'C''\u0043' The upper-case variant of 'c'.The
'-'flag defined for General conversions applies. If the'#'flag is given, then aFormatFlagsConversionMismatchExceptionwill be thrown.The width is defined as for General conversions.
The precision is not applicable. If the precision is specified then an
IllegalFormatPrecisionExceptionwill be thrown.Numeric
Numeric conversions are divided into the following categories:
Numeric types will be formatted according to the following algorithm:
Number Representation Algorithm
After digits are obtained for the integer part, fractional part, and exponent (as appropriate for the data type), the following transformation is applied:
- Each digit character d in the string is replaced by a digit computed relative to the zero digit
'0'. - If the
'0'flag is given, then the zero digits'0'are inserted after the sign character, if any, and before the first non-zero digit, until the length of the string is equal to the requested field width. - If the value is negative and the
'('flag is given, then a'('('\u0028') is prepended and a')'('\u0029') is appended. - If the value is negative (or floating-point negative zero) and
'('flag is not given, then a'-'('\u002d') is prepended. - If the
'+'flag is given and the value is positive or zero (or floating-point positive zero), then a'+'('\u002b') will be prepended.
If the value is NaN or positive infinity the literal strings "NaN" or "Infinity" respectively, will be output. If the value is negative infinity, then the output will be "(Infinity)" if the
'('flag is given otherwise the output will be "-Infinity". These values are not localized.Byte, Short, Integer, and Long
The following conversions may be applied to
byte,Byte,short,Short,intandInteger,long, andLong.'d''\u0064' Formats the argument as a decimal integer. The localization algorithm is applied. If the
'0'flag is given and the value is negative, then the zero padding will occur after the sign.If the
'#'flag is given then aFormatFlagsConversionMismatchExceptionwill be thrown.'o''\u006f' Formats the argument as an integer in base eight. No localization is applied. If x is negative then the result will be an unsigned value generated by adding 2n to the value where
nis the number of bits in the type as returned by the staticSIZEfield in the Byte, Short, Integer, or Long classes as appropriate.If the
'#'flag is given then the output will always begin with the radix indicator'0'.If the
'0'flag is given then the output will be padded with leading zeros to the field width following any indication of sign.If
'(','+', or ' ' flags are given then aFormatFlagsConversionMismatchExceptionwill be thrown.'x''\u0078' Formats the argument as an integer in base sixteen. No localization is applied. If x is negative then the result will be an unsigned value generated by adding 2n to the value where
nis the number of bits in the type as returned by the staticSIZEfield in the Byte, Short, Integer, or Long classes as appropriate.If the
'#'flag is given then the output will always begin with the radix indicator"0x".If the
'0'flag is given then the output will be padded to the field width with leading zeros after the radix indicator or sign (if present).If
'(', ' ', or'+'flags are given then aFormatFlagsConversionMismatchExceptionwill be thrown.'X''\u0058' The upper-case variant of 'x'. The entire string representing the number will be converted to upper case including the'x'(if any) and all hexadecimal digits -'f'('\u0066').If the conversion is
'o','x', or'X'and both the'#'and the'0'flags are given, then result will contain the radix indicator ('0'for octal and"0x"or"0X"for hexadecimal), some number of zeros (based on the width), and the value.If the
'-'flag is not given, then the space padding will occur before the sign.The following flags apply to numeric integral conversions:
'+''\u002b' Requires the output to include a positive sign for all positive numbers. If this flag is not given then only negative values will include a sign. If both the
'+'and ' ' flags are given then anIllegalFormatFlagsExceptionwill be thrown.' ' '\u0020' Requires the output to include a single extra space ('\u0020') for non-negative values. If both the
'+'and ' ' flags are given then anIllegalFormatFlagsExceptionwill be thrown.'0''\u0030' Requires the output to be padded with leading '0'to the minimum field width following any sign or radix indicator except when converting NaN or infinity. If the width is not provided, then aMissingFormatWidthExceptionwill be thrown.If both the
'-'and'0'flags are given then anIllegalFormatFlagsExceptionwill be thrown.',''\u002c' Requires the output to include the group separators as described in the "group" section of the localization algorithm. '(''\u0028' Requires the output to prepend a '('('\u0028') and append a')'( '\u0029') to negative values.If no flags are given the default formatting is as follows:
- The output is right-justified within the
width - Negative numbers begin with a
'-'('\u002d') - Positive numbers and zero do not include a sign or extra leading space
- No grouping separators are included
The width is the minimum number of characters to be written to the output. This includes any signs, digits, grouping separators, radix indicator, and parentheses. If the length of the converted value is less than the width then the output will be padded by spaces ('\u0020') until the total number of characters equals width. The padding is on the left by default. If
'-'flag is given then the padding will be on the right. If width is not specified then there is no minimum.The precision is not applicable. If precision is specified then an
IllegalFormatPrecisionExceptionwill be thrown.The following conversions may be applied to
float,Float,doubleandDouble.'f''\u0066' Requires the output to be formatted using decimal format. The localization algorithm is applied. The result is a string that represents the sign and magnitude (absolute value) of the argument. The formatting of the sign is described in the localization algorithm. The formatting of the magnitude m depends upon its value.
If m NaN or infinite, the literal strings "NaN" or "Infinity", respectively, will be output. These values are not localized.
The magnitude is formatted as the integer part of m, with no leading zeroes, followed by the decimal separator followed by one or more decimal digits representing the fractional part of m.
The number of digits in the result for the fractional part of m or a is equal to the precision. If the precision is not specified then the default value is
6. If the precision is less than the number of digits which would appear after the decimal point in the string returned byFloat.toString(float)orDouble.toString(double)respectively, then the result cannot be printed and aIllegalFormatConversionExceptionis thrown. Otherwise, zeros may be appended to reach the precision. For a canonical representation of the value, useFloat.toString(float)orDouble.toString(double)as appropriate.All flags defined for Byte, Short, Integer, and Long apply.
If the
'#'flag is given, then the decimal separator will always be present.If no flags are given the default formatting is as follows:
- The output is right-justified within the
width - Negative numbers begin with a
'-' - Positive numbers and positive zero do not include a sign or extra leading space
- No grouping separators are included
- The decimal separator will only appear if a digit follows it
The width is the minimum number of characters to be written to the output. This includes any signs, digits, grouping separators, decimal separators, exponential symbol, radix indicator, parentheses, and strings representing infinity and NaN as applicable. If the length of the converted value is less than the width then the output will be padded by spaces ('\u0020') until the total number of characters equals width. The padding is on the left by default. If the
'-'flag is given then the padding will be on the right. If width is not specified then there is no minimum.If the conversion is
'f', then the precision is the number of digits after the decimal separator. If the precision is not specified, then it is assumed to be6.If the conversion is
'g'or'G', then the precision is the total number of significant digits in the resulting magnitude after rounding. If the precision is not specified, then the default value is6. If the precision is0, then it is taken to be1.Percent
The conversion does not correspond to any argument.
'%'The result is a literal '%'('\u0025')The width is the minimum number of characters to be written to the output including the
'%'. If the length of the converted value is less than thewidththen the output will be padded by spaces ('\u0020') until the total number of characters equals width. The padding is on the left. If width is not specified then just the'%'is output.The
'-'flag defined for General conversions applies. If any other flags are provided, then aFormatFlagsConversionMismatchExceptionwill be thrown.The precision is not applicable. If the precision is specified an
IllegalFormatPrecisionExceptionwill be thrown.Line Separator
The conversion does not correspond to any argument.
'n'the platform-specific line separator as returned by System.getProperty("line.separator").Flags, width, and precision are not applicable. If any are provided an
IllegalFormatFlagsException,IllegalFormatWidthException, andIllegalFormatPrecisionException, respectively will be thrown.Argument Index
Format specifiers can reference arguments in three ways:
- Explicit indexing is used when the format specifier contains an argument index. The argument index is a
decimal integer indicating the position of the argument in the argument list. The first argument is referenced by
"
1$", the second by "2$", etc. An argument may be referenced more than once.For example:
formatter.format("%4$s %3$s %2$s %1$s %4$s %3$s %2$s %1$s", "a", "b", "c", "d") // -> "d c b a d c b a" - Relative indexing is used when the format specifier contains a
'<'('\u003c') flag which causes the argument for the previous format specifier to be re-used. If there is no previous argument, then aMissingFormatArgumentExceptionis thrown.formatter.format("%s %s %<s %<s", "a", "b", "c", "d") // -> "a b b b" // "c" and "d" are ignored because they are not referenced - Ordinary indexing is used when the format specifier contains neither an argument index nor a
'<'flag. Each format specifier which uses ordinary indexing is assigned a sequential implicit index into argument list which is independent of the indices used by explicit or relative indexing.formatter.format("%s %s %s %s", "a", "b", "c", "d") // -> "a b c d"
It is possible to have a format string which uses all forms of indexing, for example:
formatter.format("%2$s %s %<s %s", "a", "b", "c", "d") // -> "b a a b" // "c" and "d" are ignored because they are not referencedThe maximum number of arguments is limited by the maximum dimension of a Java array as defined by The Java™ Virtual Machine Specification. If the argument index is does not correspond to an available argument, then a
MissingFormatArgumentExceptionis thrown.If there are more arguments than format specifiers, the extra arguments are ignored.
Unless otherwise specified, passing a
nullargument to any method or constructor in this class will cause aNullPointerExceptionto be thrown.- Since:
- 1.5
-
-
Constructor Summary
Constructors Constructor Description Formatter()Constructs a new formatter.Formatter(OutputStream os)Constructs a new formatter with the specified output stream.Formatter(OutputStream os, String csn)Constructs a new formatter with the specified output stream and charset.Formatter(PrintStream ps)Constructs a new formatter with the specified print stream.Formatter(Appendable a)Constructs a new formatter with the specified destination.
-
Method Summary
All Methods Instance Methods Concrete Methods Modifier and Type Method Description voidclose()Closes this formatter.voidflush()Flushes this formatter.Formatterformat(String format, Object... args)Writes a formatted string to this object's destination using the specified format string and arguments.IOExceptionioException()Returns theIOExceptionlast thrown by this formatter'sAppendable.Appendableout()Returns the destination for the output.StringtoString()Returns the result of invokingtoString()on the destination for the output.
-
-
-
Constructor Detail
-
Formatter
public Formatter()
Constructs a new formatter.The destination of the formatted output is a
StringBuilderwhich may be retrieved by invokingout()and whose current content may be converted into a string by invokingtoString().
-
Formatter
public Formatter(@Nullable Appendable a)
Constructs a new formatter with the specified destination.- Parameters:
a- Destination for the formatted output. Ifaisnullthen aStringBuilderwill be created.
-
Formatter
public Formatter(PrintStream ps)
Constructs a new formatter with the specified print stream.Characters are written to the given
PrintStreamobject and are therefore encoded using that object's charset.- Parameters:
ps- The stream to use as the destination of this formatter.
-
Formatter
public Formatter(OutputStream os)
Constructs a new formatter with the specified output stream.The charset used is the default charset for this instance of the Java virtual machine.
- Parameters:
os- The output stream to use as the destination of this formatter. The output will be buffered.
-
Formatter
public Formatter(OutputStream os, String csn) throws UnsupportedEncodingException
Constructs a new formatter with the specified output stream and charset.- Parameters:
os- The output stream to use as the destination of this formatter. The output will be buffered.csn- The name of a supported charset.- Throws:
UnsupportedEncodingException- If the named charset is not supported.
-
-
Method Detail
-
out
public Appendable out()
Returns the destination for the output.- Returns:
- The destination for the output
- Throws:
FormatterClosedException- If this formatter has been closed by invoking itsclose()method
-
toString
public String toString()
Returns the result of invokingtoString()on the destination for the output. For example, the following code formats text into aStringBuilderthen retrieves the resultant string:Formatter f = new Formatter(); f.format("Last reboot at %tc", lastRebootDate); String s = f.toString(); // -> s == "Last reboot at Sat Jan 01 00:00:00 PST 2000"An invocation of this method behaves in exactly the same way as the invocation
out().toString()
Depending on the specification of
toStringfor theAppendable, the returned string may or may not contain the characters written to the destination. For instance, buffers typically return their contents intoString(), but streams cannot since the data is discarded.- Overrides:
toStringin classObject- Returns:
- The result of invoking
toString()on the destination for the output - Throws:
FormatterClosedException- If this formatter has been closed by invoking itsclose()method
-
flush
public void flush()
Flushes this formatter. If the destination implements theFlushableinterface, itsflushmethod will be invoked.Flushing a formatter writes any buffered output in the destination to the underlying stream.
- Specified by:
flushin interfaceFlushable- Throws:
FormatterClosedException- If this formatter has been closed by invoking itsclose()method
-
close
public void close()
Closes this formatter. If the destination implements theCloseableinterface, itsclosemethod will be invoked.Closing a formatter allows it to release resources it may be holding (such as open files). If the formatter is already closed, then invoking this method has no effect.
Attempting to invoke any methods except
ioException()in this formatter after it has been closed will result in aFormatterClosedException.- Specified by:
closein interfaceAutoCloseable- Specified by:
closein interfaceCloseable
-
ioException
@Nullable public IOException ioException()
Returns theIOExceptionlast thrown by this formatter'sAppendable.If the destination's
append()method never throwsIOException, then this method will always returnnull.- Returns:
- The last exception thrown by the Appendable or
nullif no such exception exists.
-
format
public Formatter format(String format, @Nullable Object... args)
Writes a formatted string to this object's destination using the specified format string and arguments. The locale used is the one defined during the construction of this formatter.- Parameters:
format- A format string as described in Format string syntax.args- Arguments referenced by the format specifiers in the format string. If there are more arguments than format specifiers, the extra arguments are ignored. The maximum number of arguments is limited by the maximum dimension of a Java array as defined by The Java™ Virtual Machine Specification.- Returns:
- This formatter
- Throws:
IllegalFormatException- If a format string contains an illegal syntax, a format specifier that is incompatible with the given arguments, insufficient arguments given the format string, or other illegal conditions. For specification of all possible formatting errors, see the Details section of the formatter class specification.FormatterClosedException- If this formatter has been closed by invoking itsclose()method
-
-