Class Formatter
- java.lang.Object
-
- java.util.Formatter
-
- All Implemented Interfaces:
Closeable,Flushable,AutoCloseable
public final class Formatter extends Object implements Closeable, Flushable
Formats arguments according to a format string (likeprintfin C).It's relatively rare to use a
Formatterdirectly. A variety of classes offer convenience methods for accessing formatter functionality. Of these,String.format(java.lang.String, java.lang.Object...)is generally the most useful.PrintStreamandPrintWriterboth offerformatandprintfmethods.Format strings consist of plain text interspersed with format specifiers, such as
"name: %s weight: %03dkg\n". Being a Java string, the usual Java string literal backslash escapes are of course available.Format specifiers (such as
"%s"or"%03d"in the example) start with a%and describe how to format their corresponding argument. It includes an optional argument index, optional flags, an optional width, an optional precision, and a mandatory conversion type. In the example,"%s"has no flags, no width, and no precision, while"%03d"has the flag0, the width 3, and no precision.Not all combinations of argument index, flags, width, precision, and conversion type are valid.
Argument index. Normally, each format specifier consumes the next argument to
format. For convenient localization, it's possible to reorder arguments so that they appear in a different order in the output than the order in which they were supplied. For example,"%4$s"formats the fourth argument (4$) as a string (s). It's also possible to reuse an argument with<. For example,format("%o %<d %<x", 64)results in"100 64 40".Flags. The available flags are:
Flags ,Use grouping separators for large numbers. (Decimal only.) format("%,d", 1024);1,234+Always show sign. (Decimal only.) format("%+d, %+4d", 5, 5);+5, +5
A space indicates that non-negative numbers should have a leading space. (Decimal only.) format("x% d% 5d", 4, 4);x 4 4
(Put parentheses around negative numbers. (Decimal only.) format("%(d, %(d, %(6d", 12, -12, -12);12, (12), (12)
-Left-justify. (Requires width.) format("%-6dx", 5);format("%-3C, %3C", 'd', 0x65);5 x
D , E
0Pad the number with leading zeros. (Requires width.) format("%07d, %03d", 4, 5555);0000004, 5555#Alternate form. (Octal and hex only.) format("%o %#o", 010, 010);format("%x %#x", 0x12, 0x12);10 01012 0x12Width. The width is a decimal integer specifying the minimum number of characters to be used to represent the argument. If the result would otherwise be shorter than the width, padding will be added (the exact details of which depend on the flags). Note that you can't use width to truncate a field, only to make it wider: see precision for control over the maximum width.
Precision. The precision is a
.followed by a decimal integer, giving the minimum number of digits ford,o,x, orX; the minimum number of digits after the decimal point fora,A,e,E,f, orF; the maximum number of significant digits forgorG; or the maximum number of characters forsorS.Conversion type. One or two characters describing how to interpret the argument. Most conversions are a single character, but date/time conversions all start with
tand have a single extra character describing the desired output.Many conversion types have a corresponding uppercase variant that converts its result to uppercase using the rules of the relevant locale (either the default or the locale set for this formatter).
This table shows the available single-character (non-date/time) conversion types:
String conversions
All types are acceptable arguments. Values of typeFormattablehave theirformatTomethod invoked; all other types usetoString.sString. format("%s %s", "hello", "Hello");hello HelloSUppercase string. format("%S %S", "hello", "Hello");HELLO HELLOCharacter conversions
Byte, Character, Short, and Integer (and primitives that box to those types) are all acceptable as character arguments. Any other type is an error.cCharacter. format("%c %c", 'd', 'E');d ECUppercase character. format("%C %C", 'd', 'E');D EInteger conversions
Byte, Short, Integer, Long, and BigInteger (and primitives that box to those types) are all acceptable as integer arguments. Any other type is an error.dDecimal. format("%d", 26);26oOctal. format("%o", 032);32x,XHexadecimal. format("%x %X", 0x1a, 0x1a);1a 1AFloating-point conversions
Float, Double, and BigDecimal (and primitives that box to those types) are all acceptable as floating-point arguments. Any other type is an error.fDecimal floating point. format("%f", 123.456f); format("%.1f", 123.456f); format("%1.5f", 123.456f); format("%10f", 123.456f); format("%6.0f", 123.456f);123.456001 123.5 123.45600 123.456001 123
e,EEngineering/exponential floating point. format("%e", 123.456f); format("%.1e", 123.456f); format("%1.5E", 123.456f); format("%10E", 123.456f); format("%6.0E", 123.456f);1.234560e+02 1.2e+02 1.23456E+02 1.234560E+02 1E+02
g,GDecimal or engineering, depending on the magnitude of the value. format("%g %g", 0.123, 0.0000123);0.123000 1.23000e-05a,AHexadecimal floating point. format("%a", 123.456f);0x1.edd2f2p6Boolean conversion
Accepts Boolean values.nullis considered false, and instances of all other types are considered true.b,BBoolean. format("%b %b", true, false);format("%B %B", true, false);format("%b", null);format("%b", "hello");true falseTRUE FALSEfalsetrueHash code conversion
InvokeshashCodeon its argument, which may be of any type.h,HHexadecimal hash code. format("%h", this);format("%H", this);format("%h", null);190d11190D11nullZero-argument conversions %A literal % character. format("%d%%", 50);50%nNewline. (The value of System.lineSeparator().)format("first%nsecond");first\nsecondIt's also possible to format dates and times with
Formatter, though you should useSimpleDateFormat(probably via the factory methods inDateFormat) instead. The facilities offered byFormatterare low-level and place the burden of localization on the developer. UsingDateFormat.getDateInstance(),DateFormat.getTimeInstance(), andDateFormat.getDateTimeInstance()is preferable for dates and times that will be presented to a human. Those methods will select the best format strings for the user's locale.The best non-localized form is ISO 8601, which you can get with
"%tF"(2010-01-22),"%tF %tR"(2010-01-22 13:39),"%tF %tT"(2010-01-22 13:39:15), or"%tF %tT%z"(2010-01-22 13:39:15-0800).This table shows the date/time conversions, but you should use
SimpleDateFormatinstead:Date/time conversions
Calendar, Date, and Long (representing milliseconds past the epoch) are all acceptable as date/time arguments. Any other type is an error. The epoch is 1970-01-01 00:00:00 UTC. UseSimpleDateFormatinstead.taLocalized weekday name (abbreviated). format("%ta", cal, cal);TuetALocalized weekday name (full). format("%tA", cal, cal);TuesdaytbLocalized month name (abbreviated). format("%tb", cal);AprtBLocalized month name (full). format("%tB", cal);ApriltcC library asctime(3)-like output. Do not use. format("%tc", cal);Tue Apr 01 16:19:17 CEST 2008tC2-digit century. format("%tC", cal);20td2-digit day of month (01-31). format("%td", cal);01tDAmbiguous US date format (MM/DD/YY). Do not use. format("%tD", cal);04/01/08teDay of month (1-31). format("%te", cal);1tFFull date in ISO 8601 format (YYYY-MM-DD). format("%tF", cal);2008-04-01thSynonym for %tb.tH2-digit 24-hour hour of day (00-23). format("%tH", cal);16tI2-digit 12-hour hour of day (01-12). format("%tI", cal);04tj3-digit day of year (001-366). format("%tj", cal);092tk24-hour hour of day (0-23). format("%tk", cal);16tl12-hour hour of day (1-12). format("%tl", cal);4tLMilliseconds. format("%tL", cal);359tm2-digit month of year (01-12). format("%tm", cal);04tM2-digit minute. format("%tM", cal);08tNNanoseconds. format("%tN", cal);359000000tpa.m. or p.m. format("%tp %Tp", cal, cal);pm PMtQMilliseconds since the epoch. format("%tQ", cal);1207059412656trFull 12-hour time ( %tI:%tM:%tS %Tp).format("%tr", cal);04:15:32 PMtRShort 24-hour time ( %tH:%tM).format("%tR", cal);16:15tsSeconds since the epoch. format("%ts", cal);1207059412tS2-digit seconds (00-60). format("%tS", cal);17tTFull 24-hour time ( %tH:%tM:%tS).format("%tT", cal);16:15:32ty2-digit year (00-99). format("%ty", cal);08tY4-digit year. format("%tY", cal);2008tzTime zone GMT offset. format("%tz", cal);+0100tZLocalized time zone abbreviation. format("%tZ", cal);CESTAs with the other conversions, date/time conversion has an uppercase format. Replacing
%twith%Twill uppercase the field according to the rules of the formatter's locale.Number localization. Some conversions use localized decimal digits rather than the usual ASCII digits. So formatting
123with%dwill give 123 in English locales but ١٢٣ in appropriate Arabic locales, for example. This number localization occurs for the decimal integer conversion%d, the floating point conversions%e,%f, and%g, and all date/time%tor%Tconversions, but no other conversions.Thread safety. Formatter is not thread-safe.
- Since:
- 1.5
- See Also:
DateFormat,Formattable,SimpleDateFormat
-
-
Nested Class Summary
Nested Classes Modifier and Type Class Description static classFormatter.BigDecimalLayoutFormThe enumeration giving the available styles for formatting very large decimal numbers.
-
Constructor Summary
Constructors Constructor Description Formatter()Constructs aFormatter.Formatter(File file)Constructs aFormatterwhose output is written to the specifiedFile.Formatter(File file, String csn)Constructs aFormatterwith the given charset, and whose output is written to the specifiedFile.Formatter(File file, String csn, Locale l)Constructs aFormatterwith the givenLocaleand charset, and whose output is written to the specifiedFile.Formatter(OutputStream os)Constructs aFormatterwhose output is written to the specifiedOutputStream.Formatter(OutputStream os, String csn)Constructs aFormatterwith the given charset, and whose output is written to the specifiedOutputStream.Formatter(OutputStream os, String csn, Locale l)Constructs aFormatterwith the givenLocaleand charset, and whose output is written to the specifiedOutputStream.Formatter(PrintStream ps)Constructs aFormatterwhose output is written to the specifiedPrintStream.Formatter(Appendable a)Constructs aFormatterwhose output will be written to the specifiedAppendable.Formatter(Appendable a, Locale l)Constructs aFormatterwith the specifiedLocaleand whose output will be written to the specifiedAppendable.Formatter(String fileName)Constructs aFormatterwhose output is written to the specified file.Formatter(String fileName, String csn)Constructs aFormatterwhose output is written to the specified file.Formatter(String fileName, String csn, Locale l)Constructs aFormatterwith the givenLocaleand charset, and whose output is written to the specified file.Formatter(Locale l)Constructs aFormatterwith the specifiedLocale.
-
Method Summary
All Methods Instance Methods Concrete Methods Modifier and Type Method Description voidclose()Closes theFormatter.voidflush()Flushes theFormatter.Formatterformat(String format, Object... args)Writes a formatted string to the output destination of theFormatter.Formatterformat(Locale l, String format, Object... args)Writes a formatted string to the output destination of theFormatter.IOExceptionioException()Returns the lastIOExceptionthrown by theFormatter's output destination.Localelocale()Returns theLocaleof theFormatter.Appendableout()Returns the output destination of theFormatter.StringtoString()Returns the content by calling thetoString()method of the output destination.
-
-
-
Constructor Detail
-
Formatter
public Formatter()
Constructs aFormatter.The output is written to a
StringBuilderwhich can be acquired by invokingout()and whose content can be obtained by callingtoString.The
Localeused is the user's default locale. See "Be wary of the default locale".
-
Formatter
public Formatter(Appendable a)
Constructs aFormatterwhose output will be written to the specifiedAppendable.The
Localeused is the user's default locale. See "Be wary of the default locale".- Parameters:
a- the output destination of theFormatter. Ifaisnull, then aStringBuilderwill be used.
-
Formatter
public Formatter(Locale l)
Constructs aFormatterwith the specifiedLocale.The output is written to a
StringBuilderwhich can be acquired by invokingout()and whose content can be obtained by callingtoString.- Parameters:
l- theLocaleof theFormatter. Iflisnull, then no localization will be used.
-
Formatter
public Formatter(Appendable a, Locale l)
Constructs aFormatterwith the specifiedLocaleand whose output will be written to the specifiedAppendable.- Parameters:
a- the output destination of theFormatter. Ifaisnull, then aStringBuilderwill be used.l- theLocaleof theFormatter. Iflisnull, then no localization will be used.
-
Formatter
public Formatter(String fileName) throws FileNotFoundException
Constructs aFormatterwhose output is written to the specified file.The charset of the
Formatteris the default charset.The
Localeused is the user's default locale. See "Be wary of the default locale".- Parameters:
fileName- the filename of the file that is used as the output destination for theFormatter. The file will be truncated to zero size if the file exists, or else a new file will be created. The output of theFormatteris buffered.- Throws:
FileNotFoundException- if the filename does not denote a normal and writable file, or if a new file cannot be created, or if any error arises when opening or creating the file.
-
Formatter
public Formatter(String fileName, String csn) throws FileNotFoundException, UnsupportedEncodingException
Constructs aFormatterwhose output is written to the specified file.The
Localeused is the user's default locale. See "Be wary of the default locale".- Parameters:
fileName- the filename of the file that is used as the output destination for theFormatter. The file will be truncated to zero size if the file exists, or else a new file will be created. The output of theFormatteris buffered.csn- the name of the charset for theFormatter.- Throws:
FileNotFoundException- if the filename does not denote a normal and writable file, or if a new file cannot be created, or if any error arises when opening or creating the file.UnsupportedEncodingException- if the charset with the specified name is not supported.
-
Formatter
public Formatter(String fileName, String csn, Locale l) throws FileNotFoundException, UnsupportedEncodingException
Constructs aFormatterwith the givenLocaleand charset, and whose output is written to the specified file.- Parameters:
fileName- the filename of the file that is used as the output destination for theFormatter. The file will be truncated to zero size if the file exists, or else a new file will be created. The output of theFormatteris buffered.csn- the name of the charset for theFormatter.l- theLocaleof theFormatter. Iflisnull, then no localization will be used.- Throws:
FileNotFoundException- if the filename does not denote a normal and writable file, or if a new file cannot be created, or if any error arises when opening or creating the file.UnsupportedEncodingException- if the charset with the specified name is not supported.
-
Formatter
public Formatter(File file) throws FileNotFoundException
Constructs aFormatterwhose output is written to the specifiedFile. The charset of theFormatteris the default charset.The
Localeused is the user's default locale. See "Be wary of the default locale".- Parameters:
file- theFilethat is used as the output destination for theFormatter. TheFilewill be truncated to zero size if theFileexists, or else a newFilewill be created. The output of theFormatteris buffered.- Throws:
FileNotFoundException- if theFileis not a normal and writableFile, or if a newFilecannot be created, or if any error rises when opening or creating theFile.
-
Formatter
public Formatter(File file, String csn) throws FileNotFoundException, UnsupportedEncodingException
Constructs aFormatterwith the given charset, and whose output is written to the specifiedFile.The
Localeused is the user's default locale. See "Be wary of the default locale".- Parameters:
file- theFilethat is used as the output destination for theFormatter. TheFilewill be truncated to zero size if theFileexists, or else a newFilewill be created. The output of theFormatteris buffered.csn- the name of the charset for theFormatter.- Throws:
FileNotFoundException- if theFileis not a normal and writableFile, or if a newFilecannot be created, or if any error rises when opening or creating theFile.UnsupportedEncodingException- if the charset with the specified name is not supported.
-
Formatter
public Formatter(File file, String csn, Locale l) throws FileNotFoundException, UnsupportedEncodingException
Constructs aFormatterwith the givenLocaleand charset, and whose output is written to the specifiedFile.- Parameters:
file- theFilethat is used as the output destination for theFormatter. TheFilewill be truncated to zero size if theFileexists, or else a newFilewill be created. The output of theFormatteris buffered.csn- the name of the charset for theFormatter.l- theLocaleof theFormatter. Iflisnull, then no localization will be used.- Throws:
FileNotFoundException- if theFileis not a normal and writableFile, or if a newFilecannot be created, or if any error rises when opening or creating theFile.UnsupportedEncodingException- if the charset with the specified name is not supported.
-
Formatter
public Formatter(OutputStream os)
Constructs aFormatterwhose output is written to the specifiedOutputStream.The charset of the
Formatteris the default charset.The
Localeused is the user's default locale. See "Be wary of the default locale".- Parameters:
os- the stream to be used as the destination of theFormatter.
-
Formatter
public Formatter(OutputStream os, String csn) throws UnsupportedEncodingException
Constructs aFormatterwith the given charset, and whose output is written to the specifiedOutputStream.The
Localeused is the user's default locale. See "Be wary of the default locale".- Parameters:
os- the stream to be used as the destination of theFormatter.csn- the name of the charset for theFormatter.- Throws:
UnsupportedEncodingException- if the charset with the specified name is not supported.
-
Formatter
public Formatter(OutputStream os, String csn, Locale l) throws UnsupportedEncodingException
Constructs aFormatterwith the givenLocaleand charset, and whose output is written to the specifiedOutputStream.- Parameters:
os- the stream to be used as the destination of theFormatter.csn- the name of the charset for theFormatter.l- theLocaleof theFormatter. Iflisnull, then no localization will be used.- Throws:
UnsupportedEncodingException- if the charset with the specified name is not supported.
-
Formatter
public Formatter(PrintStream ps)
Constructs aFormatterwhose output is written to the specifiedPrintStream.The charset of the
Formatteris the default charset.The
Localeused is the user's default locale. See "Be wary of the default locale".- Parameters:
ps- thePrintStreamused as destination of theFormatter. Ifpsisnull, then aNullPointerExceptionwill be raised.
-
-
Method Detail
-
locale
public Locale locale()
Returns theLocaleof theFormatter.- Returns:
- the
Localefor theFormatterornullfor noLocale. - Throws:
FormatterClosedException- if theFormatterhas been closed.
-
out
public Appendable out()
Returns the output destination of theFormatter.- Returns:
- the output destination of the
Formatter. - Throws:
FormatterClosedException- if theFormatterhas been closed.
-
toString
public String toString()
Returns the content by calling thetoString()method of the output destination.- Overrides:
toStringin classObject- Returns:
- the content by calling the
toString()method of the output destination. - Throws:
FormatterClosedException- if theFormatterhas been closed.
-
flush
public void flush()
Flushes theFormatter. If the output destination isFlushable, then the methodflush()will be called on that destination.- Specified by:
flushin interfaceFlushable- Throws:
FormatterClosedException- if theFormatterhas been closed.
-
close
public void close()
Closes theFormatter. If the output destination isCloseable, then the methodclose()will be called on that destination. If theFormatterhas been closed, then calling the this method will have no effect. Any method but theioException()that is called after theFormatterhas been closed will raise aFormatterClosedException.- Specified by:
closein interfaceAutoCloseable- Specified by:
closein interfaceCloseable
-
ioException
public IOException ioException()
Returns the lastIOExceptionthrown by theFormatter's output destination. If theappend()method of the destination does not throwIOExceptions, theioException()method will always returnnull.- Returns:
- the last
IOExceptionthrown by theFormatter's output destination.
-
format
public Formatter format(String format, Object... args)
Writes a formatted string to the output destination of theFormatter.- Parameters:
format- a format string.args- the arguments list used in theformat()method. If there are more arguments than those specified by the format string, then the additional arguments are ignored.- Returns:
- this
Formatter. - Throws:
IllegalFormatException- if the format string is illegal or incompatible with the arguments, or if fewer arguments are sent than those required by the format string, or any other illegal situation.FormatterClosedException- if theFormatterhas been closed.
-
format
public Formatter format(Locale l, String format, Object... args)
Writes a formatted string to the output destination of theFormatter.- Parameters:
l- theLocaleused in the method. Iflocaleisnull, then no localization will be applied. This parameter does not change this Formatter's defaultLocaleas specified during construction, and only applies for the duration of this call.format- a format string.args- the arguments list used in theformat()method. If there are more arguments than those specified by the format string, then the additional arguments are ignored.- Returns:
- this
Formatter. - Throws:
IllegalFormatException- if the format string is illegal or incompatible with the arguments, or if fewer arguments are sent than those required by the format string, or any other illegal situation.FormatterClosedException- if theFormatterhas been closed.
-
-