Most visited

Recently visited

Added in API level 1

Formatter

public final class Formatter
extends Object implements Closeable, Flushable

java.lang.Object
   ↳ java.util.Formatter


printf样式格式字符串的解释器。 此类提供对布局对齐和对齐的支持,数字,字符串和日期/时间数据的常用格式以及特定于语言环境的输出。 常见的Java类型,如byteBigDecimal ,并Calendar的支持。 通过Formattable接口提供针对任意用户类型的有限格式定制。

格式化程序对于多线程访问不一定安全。 线程安全是可选的,并且是本课程中用户的责任。

Java语言的格式化打印深受C的printf启发。 虽然格式字符串与C相似,但是已经进行了一些自定义以适应Java语言并利用其某些功能。 另外,Java格式化比C更严格; 例如,如果转换与标志不兼容,则会抛出异常。 在C不适用的标志被默默地忽略。 格式字符串因此旨在被C程序员识别,但不一定完全与C中的那些兼容。

预期用法的例子:

   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"

   // Optional locale as the first argument can be used to get
   // locale-specific formatting of numbers.  The precision and width can be
   // given to round and align the value.
   formatter.format(Locale.FRANCE, "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)"
 

存在常见格式化请求的便捷方法,如下面的调用所示:

   // Writes a formatted string to System.out.
   System.out.format("Local time: %tT", Calendar.getInstance());
   // -> "Local time: 13:34:18"

   // 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"
 

像C的 sprintf(3) ,可以使用静态方法 String.format对字符串进行格式化:

   // Format a string containing a date.
   import java.util.Calendar;
   import java.util.GregorianCalendar;
   import static java.util.Calendar.*;

   Calendar c = new GregorianCalendar(1995, MAY, 23);
   String s = String.format("Duke's Birthday: %1$tm %1$te,%1$tY", c);
   // -> s == "Duke's Birthday: May 23, 1995"
 

Organization

本规范分为两部分。 第一部分Summary涵盖了基本的格式化概念。 本节适用于希望快速入门并熟悉其他编程语言的格式化打印的用户。 第二部分Details涵盖了具体的实施细节。 它适用于希望更精确地指定格式化行为的用户。

Summary

本节旨在提供格式概念的简要概述。 有关精确的行为细节,请参阅Details部分。

Format String Syntax

每种产生格式化输出的方法都需要一个格式字符串和一个参数列表 格式字符串是String ,其中可能包含固定文本和一个或多个嵌入格式说明符 考虑下面的例子:

   Calendar c = ...;
   String s = String.format("Duke's Birthday: %1$tm %1$te,%1$tY", c);
 
This format string is the first argument to the format method. It contains three format specifiers " %1$tm", " %1$te", and " %1$tY" 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 "Dukes Birthday: " 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 the Calendar object c.

Conversions

转化分为以下几类:

  1. General - may be applied to any argument type
  2. Character - may be applied to basic types which represent Unicode characters: char, Character, byte, Byte, short, and Short. This conversion may also be applied to the types int and Integer when isValidCodePoint(int) returns true
  3. Numeric
    1. Integral - may be applied to Java integral types: byte, Byte, short, Short, int and Integer, long, Long, and BigInteger
    2. Floating Point - may be applied to Java floating-point types: float, Float, double, Double, and BigDecimal
  4. Date/Time - may be applied to Java types which are capable of encoding a date or time: long, Long, Calendar, and Date.
  5. Percent - produces a literal '%' ('\u0025')
  6. Line Separator - produces the platform-specific line separator

下表总结了支持的转换。 通过一个大写字符标记转换(即'B''H''S''C''X''E''G''A' ,和'T' )是相同的那些相应的小写转换字符除了将结果转换成上根据现行的Locale的规则。 结果等同于以下调用toUpperCase()

    out.toUpperCase() 
Conversion Argument Category 描述
'b', 'B' general If the argument arg is null, then the result is "false". If arg is a boolean or Boolean, then the result is the string returned by String.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 invoking Integer.toHexString(arg.hashCode()).
's', 'S' general If the argument arg is null, then the result is "null". If arg implements Formattable, then arg.formatTo is invoked. Otherwise, the result is obtained by invoking arg.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
'e', 'E' floating point The result is formatted as a decimal number in computerized scientific notation
'f' floating point The result is formatted as a decimal number
'g', 'G' floating point The result is formatted using computerized scientific notation or decimal format, depending on the precision and the value after rounding.
'a', 'A' floating point The result is formatted as a hexadecimal floating-point number with a significand and an exponent
't', 'T' date/time Prefix for date and time conversion characters. See Date/Time Conversions.
'%' percent The result is a literal '%' ('\u0025')
'n' line separator The result is the platform-specific line separator

任何未明确定义为转换的字符都是非法的,并且为未来的扩展而保留。

Date/Time Conversions

以下日期和时间转换后缀字符是为't''T'转换定义的。 这些类型与GNU date和POSIX strftime(3c)定义的类型类似,但不完全相同。 提供额外的转换类型来访问特定于Java的功能(例如,第二秒内的'L'毫秒)。

以下转换字符用于格式化时间:

'H' Hour of the day for the 24-hour clock, formatted as two digits with a leading zero as necessary i.e. 00 - 23.
'I' Hour for the 12-hour clock, formatted as two digits with a leading zero as necessary, i.e. 01 - 12.
'k' Hour of the day for the 24-hour clock, i.e. 0 - 23.
'l' Hour for the 12-hour clock, i.e. 1 - 12.
'M' Minute within the hour formatted as two digits with a leading zero as necessary, i.e. 00 - 59.
'S' Seconds within the minute, formatted as two digits with a leading zero as necessary, i.e. 00 - 60 ("60" is a special value required to support leap seconds).
'L' Millisecond within the second formatted as three digits with leading zeros as necessary, i.e. 000 - 999.
'N' Nanosecond within the second, formatted as nine digits with leading zeros as necessary, i.e. 000000000 - 999999999.
'p' Locale-specific morning or afternoon marker in lower case, e.g."am" or "pm". Use of the conversion prefix 'T' forces this output to upper case.
'z' RFC 822 style numeric time zone offset from GMT, e.g. -0800. This value will be adjusted as necessary for Daylight Saving Time. For long, Long, and Date the time zone used is the default time zone for this instance of the Java virtual machine.
'Z' A string representing the abbreviation for the time zone. This value will be adjusted as necessary for Daylight Saving Time. For long, Long, and Date the time zone used is the default time zone for this instance of the Java virtual machine. The Formatter's locale will supersede the locale of the argument (if any).
's' Seconds since the beginning of the epoch starting at 1 January 1970 00:00:00 UTC, i.e. Long.MIN_VALUE/1000 to Long.MAX_VALUE/1000.
'Q' Milliseconds since the beginning of the epoch starting at 1 January 1970 00:00:00 UTC, i.e. Long.MIN_VALUE to Long.MAX_VALUE.

以下转换字符用于格式化日期:

'B' Locale-specific full month name, e.g. "January", "February".
'b' Locale-specific abbreviated month name, e.g. "Jan", "Feb".
'h' Same as 'b'.
'A' Locale-specific full name of the day of the week, e.g. "Sunday", "Monday"
'a' Locale-specific short name of the day of the week, e.g. "Sun", "Mon"
'C' Four-digit year divided by 100, formatted as two digits with leading zero as necessary, i.e. 00 - 99
'Y' Year, formatted as at least four digits with leading zeros as necessary, e.g. 0092 equals 92 CE for the Gregorian calendar.
'y' Last two digits of the year, formatted with leading zeros as necessary, i.e. 00 - 99.
'j' Day of year, formatted as three digits with leading zeros as necessary, e.g. 001 - 366 for the Gregorian calendar.
'm' Month, formatted as two digits with leading zeros as necessary, i.e. 01 - 13.
'd' Day of month, formatted as two digits with leading zeros as necessary, i.e. 01 - 31
'e' Day of month, formatted as two digits, i.e. 1 - 31.

以下转换字符用于格式化常用日期/时间组合。

'R' Time formatted for the 24-hour clock as "%tH:%tM"
'T' Time formatted for the 24-hour clock as "%tH:%tM:%tS".
'r' Time formatted for the 12-hour clock as "%tI:%tM:%tS %Tp". The location of the morning or afternoon marker ('%Tp') may be locale-dependent.
'D' Date formatted as "%tm/%td/%ty".
'F' ISO 8601 complete date formatted as "%tY-%tm-%td".
'c' Date and time formatted as "%ta %tb %td %tT %tZ %tY", e.g. "Sun Jul 20 16:17:00 EDT 1969".

任何未明确定义为日期/时间转换后缀的字符都是非法的,并且为未来的扩展而保留。

Flags

下表总结了支持的标志。 y表示该标志对于指定的参数类型是受支持的。

Flag General Character Integral Floating Point Date/Time 描述
'-' y y y y y The result will be left-justified.
'#' y1 - y3 y - The result should use a conversion-dependent alternate form
'+' - - y4 y - The result will always include a sign
'  ' - - y4 y - The result will include a leading space for positive values
'0' - - y y - The result will be zero-padded
',' - - y2 y5 - The result will include locale-specific grouping separators
'(' - - y4 y5 - The result will enclose negative numbers in parentheses

1取决于 Formattable的定义。

2仅适用于 'd'转换。

3仅适用 'o' 'x''X'转换。

4对于 'd''o''x''X'施加到转换 BigInteger'd'施加到 byteByteshortShortintIntegerlong ,和 Long

5对于 'e''E''f''g' ,并 'G'只有转换。

任何未明确定义为标志的字符都是非法的,并且为未来的扩展而保留。

Width

宽度是写入输出的最小字符数。 对于行分隔符转换,宽度不适用; 如果提供,则会抛出异常。

Precision

对于一般参数类型,精度是要写入输出的最大字符数。

对于浮点转换'e''E''f'精度的位数小数分隔符后的数目。 如果转换结果为'g''G' ,则精度是舍入后得到的幅度中的总位数。 如果转换为'a''A' ,则不得指定精度。

对于字符,整数和日期/时间参数类型以及百分比和行分隔符转换,精度不适用; 如果提供精度,则会抛出异常。

Argument Index

参数索引是一个十进制整数,指示参数列表中参数的位置。 第一个参数由“ 1$ ”引用,第二个由“ 2$ ”等2$

按位置引用自变量的另一种方法是使用'<''\u003c' )标志,该标志导致重新使用前一个格式说明符的参数。 例如,以下两个语句会生成相同的字符串:

   Calendar c = ...;
   String s1 = String.format("Duke's Birthday: %1$tm %1$te,%1$tY", c);

   String s2 = String.format("Duke's Birthday: %1$tm %<te,%<tY", c);
 

Details

本部分旨在提供格式化的行为细节,包括条件和例外,支持的数据类型,本地化以及标志,转换和数据类型之间的交互。 有关格式化概念的概述,请参阅Summary

任何未明确定义为转换,日期/时间转换后缀或标志的字符都是非法的,并且为未来的扩展而保留。 在格式字符串中使用这样的字符将导致引发UnknownFormatConversionExceptionUnknownFormatFlagsException

如果格式说明符包含带有无效值的宽度或精度,或者其他方式不受支持, IllegalFormatPrecisionException分别引发 IllegalFormatWidthExceptionIllegalFormatPrecisionException

如果格式说明符包含不适用于相应参数的转换字符,则会引发 IllegalFormatConversionException

所有指定的异常可通过任何的抛出 format的方法 Formatter以及通过任何 format方便的方法,例如 String.formatPrintStream.printf

通过一个大写字符标记转换(即'B''H''S''C''X''E''G''A' ,和'T' )是相同的那些相应的小写转换字符除了将结果转换成上根据现行的Locale的规则。 结果等同于以下toUpperCase()调用

    out.toUpperCase() 

General

以下常规转换可应用于任何参数类型:

'b' '\u0062' Produces either "true" or "false" as returned by toString(boolean).

如果参数是null ,那么结果是“ false ”。 如果参数是booleanBoolean ,则结果是由String.valueOf()返回的字符串。 否则,结果是“ true ”。

如果给出 '#'标志,则会抛出 FormatFlagsConversionMismatchException

'B' '\u0042' The upper-case variant of 'b'.
'h' '\u0068' Produces a string representing the hash code value of the object.

如果参数argnull ,那么结果是“ null ”。 否则,通过调用Integer.toHexString(arg.hashCode())获得结果。

如果给出了 '#'标志,则会抛出 FormatFlagsConversionMismatchException

'H' '\u0048' The upper-case variant of 'h'.
's' '\u0073' Produces a string.

如果参数是null ,那么结果是“ null ”。 如果参数实现Formattable ,则调用其formatTo方法。 否则,通过调用参数toString()方法获得结果。

如果给出 '#'标志并且参数不是 Formattable ,则会引发 FormatFlagsConversionMismatchException

'S' '\u0053' The upper-case variant of 's'.

以下 flags适用于一般转换:

'-' '\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 MissingFormatWidthException will 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.

width是要写入输出的最小字符数。 如果转换值的长度小于宽度,则输出将填充'  ''\u0020' ),直到字符总数等于宽度。 默认情况下,填充位于左侧。 如果给出了'-'标志,那么填充将在右侧。 如果宽度没有被指定,那么没有最小值。

精度是要写入输出的最大字符数。 精度在宽度之前应用,因此即使宽度大于精度,输出也会被截断为precision字符。 如果未指定精度,那么对字符数量没有明确的限制。

Character

This conversion may be applied to char and Character. It may also be applied to the types byte, Byte, short, and Short, int and Integer when isValidCodePoint(int) returns true. If it returns false then an IllegalFormatCodePointException will be thrown.
'c' '\u0063' Formats the argument as a Unicode character as described in Unicode Character Representation. This may be more than one 16-bit char in the case where the argument represents a supplementary character.

如果给出了 '#'标志,则会抛出 FormatFlagsConversionMismatchException

'C' '\u0043' The upper-case variant of 'c'.

适用于General conversions'-'标志适用。 如果给出'#'标志,则会抛出FormatFlagsConversionMismatchException

宽度定义为 General conversions

精度不适用。 如果指定了精度,则会抛出IllegalFormatPrecisionException

Numeric

数字转换分为以下几类:

  1. Byte, Short, Integer, and Long
  2. BigInteger
  3. Float and Double
  4. BigDecimal

数字类型将根据以下算法进行格式化:

Number Localization Algorithm

在获得整数部分,小数部分和指数(适用于数据类型)的位数后,将应用以下转换:

  1. Each digit character d in the string is replaced by a locale-specific digit computed relative to the current locale's zero digit z; that is d -  '0'  + z.
  2. If a decimal separator is present, a locale-specific decimal separator is substituted.
  3. If the ',' ('\u002c') flag is given, then the locale-specific grouping separator is inserted by scanning the integer part of the string from least significant to most significant digits and inserting a separator at intervals defined by the locale's grouping size.
  4. If the '0' flag is given, then the locale-specific zero digits 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.
  5. If the value is negative and the '(' flag is given, then a '(' ('\u0028') is prepended and a ')' ('\u0029') is appended.
  6. If the value is negative (or floating-point negative zero) and '(' flag is not given, then a '-' ('\u002d') is prepended.
  7. If the '+' flag is given and the value is positive or zero (or floating-point positive zero), then a '+' ('\u002b') will be prepended.

如果该值为NaN或正无穷大,则分别输出字符串“NaN”或“Infinity”。 如果该值为负无穷大,则输出将为“(Infinity)”,如果'('标志被给出,则输出将为“-Infinity”。 这些值不是本地化的。

Byte, Short, Integer, and Long

以下转换可以应用于 byteByteshortShortintIntegerlong ,和 Long

'd' '\u0054' Formats the argument as a decimal integer. The localization algorithm is applied.

如果给出了 '0'标志并且该值为负值,那么零填充将发生在符号之后。

如果 '#'标志被给出,则 FormatFlagsConversionMismatchException将被抛出。

'o' '\u006f' Formats the argument as an integer in base eight. No localization is applied.

如果 x为负,那么结果将是通过添加2 n提供给值而产生一个无符号的值,其中 n是位在作为返回由静态类型的号码 SIZE在现场 ByteShortInteger ,或 Long类作为适当。

如果给出 '#'标志,那么输出总是以基数指示符 '0'开始。

如果给出了 '0'标志,那么在任何符号指示之后,输出将用前导零填充到字段宽度。

如果 '(' '+' ,''或 ','标志,则会抛出 FormatFlagsConversionMismatchException

'x' '\u0078' Formats the argument as an integer in base sixteen. No localization is applied.

如果 x为负,那么结果将是通过添加2 n提供给值而产生一个无符号的值,其中 n是位在作为返回由静态类型的号码 SIZE在现场 ByteShortInteger ,或 Long类作为适当。

如果给出 '#'标志,那么输出总是以基数指示符 "0x"开始。

如果给出 '0'标志,那么输出将填充到字段宽度,在基数指示符或符号(如果存在)之后带前导零。

如果 '(' ,'  ', '+' ,或 ','给出标志则 FormatFlagsConversionMismatchException将被抛出。

'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 'a' - 'f' ('\u0061' - '\u0066').

如果转换是 'o''x' ,或 'X'并且两个 '#''0'标志,那么结果将包含(基数指示符 '0'为八进制和 "0x""0X"为十六进制)时,一些数量的零(基于宽度)和价值。

如果没有给出 '-'标志,那么在符号前会出现空格填充。

以下 flags适用于数字整数转换:

'+' '\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.

如果 '+''  '标志都给出,则会引发 IllegalFormatFlagsException

'  ' '\u0020' Requires the output to include a single extra space ('\u0020') for non-negative values.

如果给出 '+''  '标志,则会引发 IllegalFormatFlagsException

'0' '\u0030' Requires the output to be padded with leading zeros to the minimum field width following any sign or radix indicator except when converting NaN or infinity. If the width is not provided, then a MissingFormatWidthException will be thrown.

如果给出了 '-''0'标志,则会引发 IllegalFormatFlagsException

',' '\u002c' Requires the output to include the locale-specific 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.

如果没有给出 flags ,则默认格式如下:

width是要写入输出的最小字符数。 这包括任何符号,数字,分组分隔符,基数指示符和括号。 如果转换后的值的长度小于宽度,则输出将填充空格( '\u0020' ),直到字符总数等于宽度。 默认情况下,填充位于左侧。 如果给出了'-'标志,那么填充将在右侧。 如果没有指定宽度,那么没有最小值。

精度不适用。 如果指定精度,则会抛出IllegalFormatPrecisionException

BigInteger

以下转换可能适用于 BigInteger

'd' '\u0054' Requires the output to be formatted as a decimal integer. The localization algorithm is applied.

如果 '#'标志被给出,则会抛出 FormatFlagsConversionMismatchException

'o' '\u006f' Requires the output to be formatted as an integer in base eight. No localization is applied.

如果x为负,那么结果将是一个以'-''\u002d' )开头的有符号值。 对于这种类型,允许签名输出,因为与原始类型不同,不可能在不假设明确的数据类型大小的情况下创建无符号的等价类。

如果 x为正或零,并给出 '+'标志,则结果将以 '+''\u002b' )开头。

如果给出 '#'标志,那么输出始终以 '0'前缀开头。

如果给出了 '0'标志,那么在任何符号的指示之后,输出将用前导零填充到字段宽度。

如果 ','标志被给出,那么 FormatFlagsConversionMismatchException将被抛出。

'x' '\u0078' Requires the output to be formatted as an integer in base sixteen. No localization is applied.

如果x是负值,那么结果将是一个以'-''\u002d' )开头的有符号值。 对于这种类型,允许签名输出,因为与原始类型不同,不可能在不假设明确的数据类型大小的情况下创建无符号的等价类。

如果 x为正或零,并给出 '+'标志,则结果将以 '+''\u002b' )开头。

如果给出 '#'标志,那么输出总是以基数指示符 "0x"开始。

如果给出了 '0'标志,则输出将填充到字段宽度,并在基数指示符或符号(如果存在)后带前导零。

如果 ','标志被给出,则 FormatFlagsConversionMismatchException将被抛出。

'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 'a' - 'f' ('\u0061' - '\u0066').

如果转换是 'o''x' ,或 'X'并且两个 '#''0'标志,那么结果将包含(基座指示器 '0'为八进制和 "0x""0X"为十六进制)时,一些数量的零(基于宽度)和价值。

如果给出了 '0'标志并且该值为负值,那么零填充将在符号之后发生。

如果没有给出 '-'标志,那么空格填充将发生在符号之前。

所有为Byte,Short,Integer和Long定义的flags都适用。 未给出标志时的default behavior与Byte,Short,Integer和Long相同。

规范 width与为Byte,Short,Integer和Long定义的相同。

精度不适用。 如果指定精度,则会抛出IllegalFormatPrecisionException

Float and Double

以下转换可以应用于 floatFloatdoubleDouble

'e' '\u0065' Requires the output to be formatted using computerized scientific notation. The localization algorithm is applied.

幅度 m的格式取决于其值。

如果m是NaN或无限,则分别输出字符串“NaN”或“Infinity”。 这些值不是本地化的。

如果 m是正零或负零,那么指数将是 "+00"

否则,结果是一个表示参数的符号和大小(绝对值)的字符串。 标志的格式在localization algorithm中描述。 幅度m的格式取决于其值。

n是唯一整数,使得10 n <= m <10 n +1 ; 然后让一个m的精确算术商和10 牛顿 ,使得1 <= 一个 <10.然后将大小被表示为a的整数部分,作为一个单一的十进制数字,然后是小数分隔后跟十进制数字表示小数部分,接着是小写区域设置特定的exponent separator (例如'e' ),其次是指数符号,随后为十进制整数n的表示,作为由该方法制备toString(long, int) ,和零填充以包含至少两位数字。

ma的小数部分的结果中的位数等于精度。 如果未指定精度,则默认值为6 如果精度小于分别由toString(float)toString(double)返回的字符串中的小数点后面出现的数字位数,则将使用round half up algorithm对该值进行四舍五入。 否则,可以附加零以达到精度。 有关该值的标准表示toString(double) ,请酌情使用toString(float)toString(double)

如果给出 ','标志,则会抛出 FormatFlagsConversionMismatchException

'E' '\u0045' The upper-case variant of 'e'. The exponent symbol will be the upper-case locale-specific exponent separator (e.g. 'E').
'g' '\u0067' Requires the output to be formatted in general scientific notation as described below. The localization algorithm is applied.

经过四舍五入的精度后,得到的幅度 m的格式取决于其值。

如果 m大于或等于10 -4但小于10 精度则在表示 decimal format

如果 m是大于或等于10 精度小于10 -4,则在表示 computerized scientific notation

m中有效数字的总数等于精度。 如果未指定精度,则默认值为6 如果精度是0 ,那么它被认为是1

如果 '#'标志被给出,那么 FormatFlagsConversionMismatchException将被抛出。

'G' '\u0047' The upper-case variant of 'g'.
'f' '\u0066' Requires the output to be formatted using decimal format. The localization algorithm is applied.

结果是一个表示参数的符号和大小(绝对值)的字符串。 标志的格式在localization algorithm中描述。 幅度m的格式取决于其值。

m NaN或无穷大,所述文本字符串“NaN”或“无限”,分别将输出。 这些值不是本地化的。

幅度被格式化为 m的整数部分,没有前导零,后面是小数分隔符,后面跟着一个或多个小数位,代表 m的小数部分。

ma的小数部分的结果中的位数等于精度。 如果未指定精度,则默认值为6 如果精度小于分别由toString(float)toString(double)返回的字符串中的小数点后面出现的位数,则将使用round half up algorithm四舍五入该值。 否则,可以附加零以达到精度。 对于该值的标准表示,视情况使用toString(float)toString(double)

'a' '\u0061' Requires the output to be formatted in hexadecimal exponential form. No localization is applied.

结果是一个表示参数 x的符号和大小(绝对值)的字符串。

如果 x为负值或负零值,则结果将以 '-''\u002d' )开头。

如果 x为正值或正值为零,并给出 '+'标志,则结果将以 '+''\u002b' )开头。

幅度 m的格式取决于其值。

  • If the value is NaN or infinite, the literal strings "NaN" or "Infinity", respectively, will be output.
  • If m is zero then it is represented by the string "0x0.0p0".
  • If m is a double value with a normalized representation then substrings are used to represent the significand and exponent fields. The significand is represented by the characters "0x1." followed by the hexadecimal representation of the rest of the significand as a fraction. The exponent is represented by 'p' ('\u0070') followed by a decimal string of the unbiased exponent as if produced by invoking Integer.toString on the exponent value.
  • If m is a double value with a subnormal representation then the significand is represented by the characters '0x0.' followed by the hexadecimal representation of the rest of the significand as a fraction. The exponent is represented by 'p-1022'. Note that there must be at least one nonzero digit in a subnormal significand.

如果给出了 '('','标志,则会抛出 FormatFlagsConversionMismatchException

'A' '\u0041' The upper-case variant of 'a'. The entire string representing the number will be converted to upper case including the 'x' ('\u0078') and 'p' ('\u0070' and all hexadecimal digits 'a' - 'f' ('\u0061' - '\u0066').

为Byte,Short,Integer和Long定义的所有 flags都适用。

如果给出了 '#'标志,则小数分隔符将始终存在。

如果没有给出 flags ,则默认格式如下:

width是要写入输出的最小字符数。 这包括任何符号,数字,分组分隔符,小数分隔符,指数符号,基数指示符,圆括号和表示无穷大和NaN的字符串(如适用)。 如果转换值的长度小于宽度,则输出将被空格( '\u0020' )填充,直到字符的总数等于宽度。 默认情况下,填充位于左侧。 如果给出'-'标志,则填充将在右侧。 如果没有指定宽度,那么没有最小值。

如果conversion'e''E''f' ,则精度是数字的小数分隔后的位数。 如果未指定精度,则假定为6

如果转换是'g''G' ,那么精度是四舍五入后得到的幅度中的有效位数的总数。 如果未指定精度,则默认值为6 如果精度是0 ,那么它被认为是1

如果转换结果为'a''A' ,则精度是小数点分隔符后的十六进制数字的数量。 如果未提供精度,则将输出由toHexString(double)返回的所有数字。

BigDecimal

以下转换可应用于 BigDecimal

'e' '\u0065' Requires the output to be formatted using computerized scientific notation. The localization algorithm is applied.

幅度 m的格式取决于其值。

如果 m是正零或负零,那么指数将是 "+00"

否则,结果是一个表示参数的符号和大小(绝对值)的字符串。 标志的格式描述在localization algorithm中 幅度m的格式取决于其值。

n是唯一整数,使得10 n <= m <10 n +1 ; 然后让一个m的精确算术商和10 牛顿 ,使得1 <= 一个 <10.然后将大小被表示为a的整数部分,作为一个单一的十进制数字,然后是小数分隔后跟十进制数字表示小数部分,随后是指数符号'e' ('\u0065'),其次是指数符号,随后为十进制整数n的表示,作为由该方法制备toString(long, int) ,并用零填充到包括至少两位数字。

ma的小数部分的结果中的位数等于精度。 如果未指定精度,则默认值为6 如果精度小于小数点右侧的位数,则该值将使用round half up algorithm进行四舍五入。 否则,可以附加零以达到精度。 对于值的标准表示,请使用toString()

如果给出了 ','标志,则会抛出 FormatFlagsConversionMismatchException

'E' '\u0045' The upper-case variant of 'e'. The exponent symbol will be 'E' ('\u0045').
'g' '\u0067' Requires the output to be formatted in general scientific notation as described below. The localization algorithm is applied.

经过四舍五入的精度后,得到的幅度 m的格式取决于其值。

如果 m大于或等于10 -4但小于10的 精度 ,则表示为 decimal format

如果 m小于10 -4或大于或等于10 精度 ,则它表示为 computerized scientific notation

m中有效数字的总数等于精度。 如果未指定精度,则默认值为6 如果精度是0 ,那么它被认为是1

如果 '#'标志被给出,则 FormatFlagsConversionMismatchException将被抛出。

'G' '\u0047' The upper-case variant of 'g'.
'f' '\u0066' Requires the output to be formatted using decimal format. The localization algorithm is applied.

结果是一个表示参数的符号和大小(绝对值)的字符串。 标志的格式描述在localization algorithm中 幅度m的格式取决于其值。

幅度被格式化为 m的整数部分,没有前导零,后面是小数分隔符,后面跟着一个或多个小数位,代表 m的小数部分。

ma的小数部分的结果中的位数等于精度。 如果未指定精度,则默认值为6 如果精度小于小数点右侧的位数,则该值将使用round half up algorithm进行四舍五入。 否则,可以附加零以达到精度。 对于值的标准表示,请使用toString()

对于Byte,Short,Integer和Long定义的所有 flags都适用。

如果给出了 '#'标志,那么小数点分隔符将始终存在。

没有标志时, default behavior与Float和Double相同。

widthprecision的规格与为Float和Double定义的规格相同。

Date/Time

这种转换可以应用于 longLongCalendar ,和 Date

't' '\u0074' Prefix for date and time conversion characters.
'T' '\u0054' The upper-case variant of 't'.

以下日期和时间转换字符后缀为't''T'转换定义。 这些类型与GNU date和POSIX strftime(3c)定义的类型类似但不完全相同。 提供了额外的转换类型来访问特定于Java的功能(例如,在第二秒内以毫秒为单位的'L' )。

以下转换字符用于格式化时间:

'H' '\u0048' Hour of the day for the 24-hour clock, formatted as two digits with a leading zero as necessary i.e. 00 - 23. 00 corresponds to midnight.
'I' '\u0049' Hour for the 12-hour clock, formatted as two digits with a leading zero as necessary, i.e. 01 - 12. 01 corresponds to one o'clock (either morning or afternoon).
'k' '\u006b' Hour of the day for the 24-hour clock, i.e. 0 - 23. 0 corresponds to midnight.
'l' '\u006c' Hour for the 12-hour clock, i.e. 1 - 12. 1 corresponds to one o'clock (either morning or afternoon).
'M' '\u004d' Minute within the hour formatted as two digits with a leading zero as necessary, i.e. 00 - 59.
'S' '\u0053' Seconds within the minute, formatted as two digits with a leading zero as necessary, i.e. 00 - 60 ("60" is a special value required to support leap seconds).
'L' '\u004c' Millisecond within the second formatted as three digits with leading zeros as necessary, i.e. 000 - 999.
'N' '\u004e' Nanosecond within the second, formatted as nine digits with leading zeros as necessary, i.e. 000000000 - 999999999. The precision of this value is limited by the resolution of the underlying operating system or hardware.
'p' '\u0070' Locale-specific morning or afternoon marker in lower case, e.g."am" or "pm". Use of the conversion prefix 'T' forces this output to upper case. (Note that 'p' produces lower-case output. This is different from GNU date and POSIX strftime(3c) which produce upper-case output.)
'z' '\u007a' RFC 822 style numeric time zone offset from GMT, e.g. -0800. This value will be adjusted as necessary for Daylight Saving Time. For long, Long, and Date the time zone used is the default time zone for this instance of the Java virtual machine.
'Z' '\u005a' A string representing the abbreviation for the time zone. This value will be adjusted as necessary for Daylight Saving Time. For long, Long, and Date the time zone used is the default time zone for this instance of the Java virtual machine. The Formatter's locale will supersede the locale of the argument (if any).
's' '\u0073' Seconds since the beginning of the epoch starting at 1 January 1970 00:00:00 UTC, i.e. Long.MIN_VALUE/1000 to Long.MAX_VALUE/1000.
'Q' '\u004f' Milliseconds since the beginning of the epoch starting at 1 January 1970 00:00:00 UTC, i.e. Long.MIN_VALUE to Long.MAX_VALUE. The precision of this value is limited by the resolution of the underlying operating system or hardware.

以下转换字符用于格式化日期:

'B' '\u0042' Locale-specific full month name, e.g. "January", "February".
'b' '\u0062' Locale-specific abbreviated month name, e.g. "Jan", "Feb".
'h' '\u0068' Same as 'b'.
'A' '\u0041' Locale-specific full name of the day of the week, e.g. "Sunday", "Monday"
'a' '\u0061' Locale-specific short name of the day of the week, e.g. "Sun", "Mon"
'C' '\u0043' Four-digit year divided by 100, formatted as two digits with leading zero as necessary, i.e. 00 - 99
'Y' '\u0059' Year, formatted to at least four digits with leading zeros as necessary, e.g. 0092 equals 92 CE for the Gregorian calendar.
'y' '\u0079' Last two digits of the year, formatted with leading zeros as necessary, i.e. 00 - 99.
'j' '\u006a' Day of year, formatted as three digits with leading zeros as necessary, e.g. 001 - 366 for the Gregorian calendar. 001 corresponds to the first day of the year.
'm' '\u006d' Month, formatted as two digits with leading zeros as necessary, i.e. 01 - 13, where "01" is the first month of the year and ("13" is a special value required to support lunar calendars).
'd' '\u0064' Day of month, formatted as two digits with leading zeros as necessary, i.e. 01 - 31, where "01" is the first day of the month.
'e' '\u0065' Day of month, formatted as two digits, i.e. 1 - 31 where "1" is the first day of the month.

以下转换字符用于格式化常用日期/时间组合。

'R' '\u0052' Time formatted for the 24-hour clock as "%tH:%tM"
'T' '\u0054' Time formatted for the 24-hour clock as "%tH:%tM:%tS".
'r' '\u0072' Time formatted for the 12-hour clock as "%tI:%tM:%tS %Tp". The location of the morning or afternoon marker ('%Tp') may be locale-dependent.
'D' '\u0044' Date formatted as "%tm/%td/%ty".
'F' '\u0046' ISO 8601 complete date formatted as "%tY-%tm-%td".
'c' '\u0063' Date and time formatted as "%ta %tb %td %tT %tZ %tY", e.g. "Sun Jul 20 16:17:00 EDT 1969".

适用于General conversions'-'标志适用。 如果'#'标志被给出,则FormatFlagsConversionMismatchException将被抛出。

width是要写入输出的最小字符数。 如果转换后的值的长度小于width则输出将填充空格( '\u0020' ),直到字符总数等于宽度。 默认情况下,填充位于左侧。 如果给出'-'标志,那么填充将在右侧。 如果没有指定宽度,那么没有最小值。

精度不适用。 如果指定了精度,则会抛出IllegalFormatPrecisionException

Percent

转换不符合任何参数。

'%' The result is a literal '%' ('\u0025')

width是写入输出的最小字符数,包括'%' 如果转换值的长度小于width则输出将被填充空格( '\u0020' ),直到字符的总数等于宽度。 填充位于左侧。 如果没有指定宽度,那么只输出'%'

适用于General conversions'-'标志适用。 如果提供了其他标志,则会抛出FormatFlagsConversionMismatchException

精度不适用。 如果指定了IllegalFormatPrecisionException则会抛出IllegalFormatPrecisionException

Line Separator

转换不符合任何参数。

'n' the platform-specific line separator as returned by System.getProperty("line.separator").

标志,宽度和精度不适用。 如果任何提供的IllegalFormatFlagsExceptionIllegalFormatWidthException ,并IllegalFormatPrecisionException ,分别将被抛出。

Argument Index

格式说明符可以通过三种方式引用参数:

可以使用所有形式的索引的格式字符串,例如:

   formatter.format("%2$s %s %<s %s", "a", "b", "c", "d")
   // -> "b a a b"
   // "c" and "d" are ignored because they are not referenced
 

参数的最大数量由The Java™ Virtual Machine Specification定义的Java数组的最大维数限制。 如果参数索引不符合可用参数,则会引发MissingFormatArgumentException

如果有比格式说明符更多的参数,则会忽略额外的参数。

除非另有说明,否则将 null参数传递给 null中的任何方法或构造函数将导致引发 NullPointerException

Summary

Nested classes

枚举 Formatter.BigDecimalLayoutForm

 

Public constructors

Formatter()

构造一个新的格式化程序。

Formatter(Appendable a)

用指定的目标构造一个新的格式化程序。

Formatter(Locale l)

用指定的语言环境构造一个新的格式器。

Formatter(Appendable a, Locale l)

使用指定的目标和区域设置构造一个新的格式器。

Formatter(String fileName)

用指定的文件名构造一个新的格式化程序。

Formatter(String fileName, String csn)

用指定的文件名和字符集构造一个新的格式器。

Formatter(String fileName, String csn, Locale l)

使用指定的文件名,字符集和区域设置构造一个新的格式器。

Formatter(File file)

用指定的文件构造一个新的格式化程序。

Formatter(File file, String csn)

用指定的文件和字符集构造一个新的格式器。

Formatter(File file, String csn, Locale l)

用指定的文件,字符集和区域设置构造一个新的格式器。

Formatter(PrintStream ps)

用指定的打印流构造一个新的格式器。

Formatter(OutputStream os)

用指定的输出流构造一个新的格式化程序。

Formatter(OutputStream os, String csn)

用指定的输出流和字符集构造一个新的格式器。

Formatter(OutputStream os, String csn, Locale l)

使用指定的输出流,字符集和区域设置构造一个新的格式器。

Public methods

void close()

关闭这个格式化程序。

void flush()

刷新此格式化程序。

Formatter format(Locale l, String format, Object... args)

使用指定的区域设置,格式字符串和参数将格式化的字符串写入此对象的目标。

Formatter format(String format, Object... args)

使用指定的格式字符串和参数将格式化的字符串写入此对象的目标。

IOException ioException()

返回此格式化程序 IOException最后抛出的 Appendable

Locale locale()

返回构造此格式化程序所设置的区域设置。

Appendable out()

返回输出的目的地。

String toString()

返回在输出的目标上调用 toString()的结果。

Inherited methods

From class java.lang.Object
From interface java.io.Closeable
From interface java.io.Flushable
From interface java.lang.AutoCloseable

Public constructors

Formatter

Added in API level 1
Formatter ()

构造一个新的格式化程序。

格式化输出的目的地是StringBuilder其可以通过调用被检索out()并且其当前内容可以通过调用被转换成字符串toString() 使用的语言环境是Java虚拟机的此实例的default locale

Formatter

Added in API level 1
Formatter (Appendable a)

用指定的目标构造一个新的格式化程序。

使用的语言环境是Java虚拟机的此实例的 default locale

Parameters
a Appendable: Destination for the formatted output. If a is null then a StringBuilder will be created.

Formatter

Added in API level 1
Formatter (Locale l)

用指定的语言环境构造一个新的格式器。

格式化输出的目的地是 StringBuilder其可以通过调用被检索 out()并且其当前内容可以通过调用被转换成字符串 toString()

Parameters
l Locale: The locale to apply during formatting. If l is null then no localization is applied.

Formatter

Added in API level 1
Formatter (Appendable a, 
                Locale l)

使用指定的目标和区域设置构造一个新的格式器。

Parameters
a Appendable: Destination for the formatted output. If a is null then a StringBuilder will be created.
l Locale: The locale to apply during formatting. If l is null then no localization is applied.

Formatter

Added in API level 1
Formatter (String fileName)

用指定的文件名构造一个新的格式化程序。

使用的字符集是Java虚拟机的这个实例的 default charset

使用的语言环境是Java虚拟机的此实例的 default locale

Parameters
fileName String: The name of the file to use as the destination of this formatter. If the file exists then it will be truncated to zero size; otherwise, a new file will be created. The output will be written to the file and is buffered.
Throws
SecurityException If a security manager is present and checkWrite(fileName) denies write access to the file
FileNotFoundException If the given file name does not denote an existing, writable regular file and a new regular file of that name cannot be created, or if some other error occurs while opening or creating the file

Formatter

Added in API level 1
Formatter (String fileName, 
                String csn)

用指定的文件名和字符集构造一个新的格式器。

使用的语言环境是Java虚拟机的此实例的 default locale

Parameters
fileName String: The name of the file to use as the destination of this formatter. If the file exists then it will be truncated to zero size; otherwise, a new file will be created. The output will be written to the file and is buffered.
csn String: The name of a supported charset
Throws
FileNotFoundException If the given file name does not denote an existing, writable regular file and a new regular file of that name cannot be created, or if some other error occurs while opening or creating the file
SecurityException If a security manager is present and checkWrite(fileName) denies write access to the file
UnsupportedEncodingException If the named charset is not supported

Formatter

Added in API level 1
Formatter (String fileName, 
                String csn, 
                Locale l)

使用指定的文件名,字符集和区域设置构造一个新的格式器。

Parameters
fileName String: The name of the file to use as the destination of this formatter. If the file exists then it will be truncated to zero size; otherwise, a new file will be created. The output will be written to the file and is buffered.
csn String: The name of a supported charset
l Locale: The locale to apply during formatting. If l is null then no localization is applied.
Throws
FileNotFoundException If the given file name does not denote an existing, writable regular file and a new regular file of that name cannot be created, or if some other error occurs while opening or creating the file
SecurityException If a security manager is present and checkWrite(fileName) denies write access to the file
UnsupportedEncodingException If the named charset is not supported

Formatter

Added in API level 1
Formatter (File file)

用指定的文件构造一个新的格式化程序。

所使用的字符集是用于此Java虚拟机实例的 default charset

使用的语言环境是此虚拟机实例的 default locale

Parameters
file File: The file to use as the destination of this formatter. If the file exists then it will be truncated to zero size; otherwise, a new file will be created. The output will be written to the file and is buffered.
Throws
SecurityException If a security manager is present and checkWrite(file.getPath()) denies write access to the file
FileNotFoundException If the given file object does not denote an existing, writable regular file and a new regular file of that name cannot be created, or if some other error occurs while opening or creating the file

Formatter

Added in API level 1
Formatter (File file, 
                String csn)

用指定的文件和字符集构造一个新的格式器。

使用的语言环境是Java虚拟机的此实例的 default locale

Parameters
file File: The file to use as the destination of this formatter. If the file exists then it will be truncated to zero size; otherwise, a new file will be created. The output will be written to the file and is buffered.
csn String: The name of a supported charset
Throws
FileNotFoundException If the given file object does not denote an existing, writable regular file and a new regular file of that name cannot be created, or if some other error occurs while opening or creating the file
SecurityException If a security manager is present and checkWrite(file.getPath()) denies write access to the file
UnsupportedEncodingException If the named charset is not supported

Formatter

Added in API level 1
Formatter (File file, 
                String csn, 
                Locale l)

用指定的文件,字符集和区域设置构造一个新的格式器。

Parameters
file File: The file to use as the destination of this formatter. If the file exists then it will be truncated to zero size; otherwise, a new file will be created. The output will be written to the file and is buffered.
csn String: The name of a supported charset
l Locale: The locale to apply during formatting. If l is null then no localization is applied.
Throws
FileNotFoundException If the given file object does not denote an existing, writable regular file and a new regular file of that name cannot be created, or if some other error occurs while opening or creating the file
SecurityException If a security manager is present and checkWrite(file.getPath()) denies write access to the file
UnsupportedEncodingException If the named charset is not supported

Formatter

Added in API level 1
Formatter (PrintStream ps)

用指定的打印流构造一个新的格式器。

使用的语言环境是此虚拟机实例的 default locale

字符被写入给定的 PrintStream对象,因此使用该对象的字符集进行编码。

Parameters
ps PrintStream: The stream to use as the destination of this formatter.

Formatter

Added in API level 1
Formatter (OutputStream os)

用指定的输出流构造一个新的格式化程序。

所使用的字符集是用于此Java虚拟机实例的 default charset

使用的语言环境是Java虚拟机的此实例的 default locale

Parameters
os OutputStream: The output stream to use as the destination of this formatter. The output will be buffered.

Formatter

Added in API level 1
Formatter (OutputStream os, 
                String csn)

用指定的输出流和字符集构造一个新的格式器。

使用的语言环境是Java虚拟机的此实例的 default locale

Parameters
os OutputStream: The output stream to use as the destination of this formatter. The output will be buffered.
csn String: The name of a supported charset
Throws
UnsupportedEncodingException If the named charset is not supported

Formatter

Added in API level 1
Formatter (OutputStream os, 
                String csn, 
                Locale l)

使用指定的输出流,字符集和区域设置构造一个新的格式器。

Parameters
os OutputStream: The output stream to use as the destination of this formatter. The output will be buffered.
csn String: The name of a supported charset
l Locale: The locale to apply during formatting. If l is null then no localization is applied.
Throws
UnsupportedEncodingException If the named charset is not supported

Public methods

close

Added in API level 1
void close ()

关闭这个格式化程序。 如果目的地实现了Closeable接口,则其close方法将被调用。

关闭一个格式化程序允许它释放可能持有的资源(如打开的文件)。 如果格式化程序已关闭,则调用此方法不起作用。

尝试在格式器关闭后调用 ioException()以外的任何方法将导致 FormatterClosedException

flush

Added in API level 1
void flush ()

刷新此格式化程序。 如果目标实现了Flushable接口,则它的flush方法将被调用。

刷新格式化程序将目标中的任何缓冲输出写入基础流。

Throws
FormatterClosedException If this formatter has been closed by invoking its close() method

format

Added in API level 1
Formatter format (Locale l, 
                String format, 
                Object... args)

使用指定的区域设置,格式字符串和参数将格式化的字符串写入此对象的目标。

Parameters
l Locale: The locale to apply during formatting. If l is null then no localization is applied. This does not change this object's locale that was set during construction.
format String: A format string as described in Format string syntax
args Object: 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
Formatter 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 its close() method

format

Added in API level 1
Formatter format (String format, 
                Object... args)

使用指定的格式字符串和参数将格式化的字符串写入此对象的目标。 使用的语言环境是在构建此格式化程序时定义的语言环境。

Parameters
format String: A format string as described in Format string syntax.
args Object: 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
Formatter 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 its close() method

ioException

Added in API level 1
IOException ioException ()

返回此格式化程序 IOException最后抛出的 Appendable

如果目标的方法 append()从不抛出 IOException ,那么此方法将始终返回 null

Returns
IOException The last exception thrown by the Appendable or null if no such exception exists.

locale

Added in API level 1
Locale locale ()

返回构造此格式化程序所设置的区域设置。

具有区域设置参数的此对象的 format方法不会更改此值。

Returns
Locale null if no localization is applied, otherwise a locale
Throws
FormatterClosedException If this formatter has been closed by invoking its close() method

out

Added in API level 1
Appendable out ()

返回输出的目的地。

Returns
Appendable The destination for the output
Throws
FormatterClosedException If this formatter has been closed by invoking its close() method

toString

Added in API level 1
String toString ()

返回在输出的目标上调用toString()的结果。 例如,以下代码将文本格式化为StringBuilder然后检索结果字符串:

   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"
 

此方法的调用的行为与调用完全相同

     out().toString() 

根据toStringAppendable ,返回的字符串可能包含或不包含写入目标的字符。 例如,缓冲区通常在toString()返回它们的内容,但由于数据被丢弃,所以流不能。

Returns
String The result of invoking toString() on the destination for the output
Throws
FormatterClosedException If this formatter has been closed by invoking its close() method

Hooray!