模块  java.base
软件包  java.util

Class Formatter

  • 实现的所有接口
    CloseableFlushableAutoCloseable

    public final class Formatter
    extends Object
    implements Closeable, Flushable
    printf样式格式字符串的解释器。 此类提供对布局对齐和对齐的支持,数字,字符串和日期/时间数据的常用格式以及特定于语言环境的输出。 常见的Java类型,如byteBigDecimalCalendar的支持。 通过Formattable界面提供对任意用户类型的有限格式自定义。

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

    C语言printf灵感源自Java语言的格式化打印。 尽管格式字符串与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$tb %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);
     
    此格式字符串是format方法的第一个参数。 它包含三个格式说明符“ %1$tm ”,“ %1$te ”和“ %1$tY ”,它们指示应如何处理参数以及它们应在文本中插入的位置。 格式字符串的其余部分是固定文本,包括"Dukes Birthday: "和任何其他空格或标点符号。 参数列表包含格式字符串后传递给方法的所有参数。 在上面的示例中,参数列表的大小为1,由Calendar对象c
    • 通用,字符和数字类型的格式说明符具有以下语法:
         %[argument_index$][flags][width][.precision]conversion
       

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

      可选标志是一组修改输出格式的字符。 有效标志集取决于转换。

      可选宽度是正十进制整数,表示要写入输出的最小字符数。

      可选精度是一个非负十进制整数,通常用于限制字符数。 具体行为取决于转换。

      所需的转换是一个字符,指示如何格式化参数。 给定参数的有效转换集取决于参数的数据类型。

    • 用于表示日期和时间的类型的格式说明符具有以下语法:
         %[argument_index$][flags][width]conversion
       

      可选的argument_indexflagswidth定义如上。

      所需的转换是两个字符的序列。 第一个字符是't''T' 第二个字符表示要使用的格式。 这些字符与GNU date和POSIX strftime(3c)定义的字符类似但不完全相同。

    • 与参数不对应的格式说明符具有以下语法:
         %[flags][width]conversion
       

      可选的标志宽度定义如上。

      所需的转换是指示要在输出中插入的内容的字符。

    转换

    转化分为以下几类:

    1. 常规 - 可以应用于任何参数类型
    2. 字符 -可以被施加到其代表的Unicode字符基本类型: charCharacterbyteByteshort ,和Short Character.isValidCodePoint(int)返回true时,此转换也可能适用于intInteger类型
    3. 数字
      1. 积分 -可应用于Java的整数类型: byteByteshortShortintIntegerlongLongBigInteger (但不charCharacter
      2. 浮点 -可用于Java的浮点类型: floatFloatdoubleDoubleBigDecimal
    4. 日期/时间 -可以被施加到Java类型,其能够编码的日期或时间的: longLongCalendarDateTemporalAccessor
    5. 百分比 - 产生文字'%''\u0025'
    6. 行分隔符 - 生成特定于平台的行分隔符

    对于A类普通性格数字小积分日期/时间转换,除非另有规定,如果参数argnull ,那么结果是“ null ”。

    下表总结了支持的转换。 通过一个大写字符标记转换(即'B''H''S''C''X''E''G''A' ,和'T' )是相同的那些相应的小写转换字符除了将结果转换成上案件根据现行规则Locale 如果没有指定显式语言环境,无论是在构造实例还是作为其方法调用的参数,都使用default locale

    genConv Conversion Argument Category Description '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 The result is obtained by invoking Integer.toHexString(arg.hashCode()). 's', 'S' general 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. This conversion is not supported for the BigDecimal type despite the latter's being in the floating point argument category. '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' ,秒内的毫秒)。

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

    time '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.

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

    date '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.

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

    composites '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".

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

    下表总结了支持的标志。 y表示指示的参数类型支持该标志。

    genConv Flag General Character Integral Floating Point Date/Time Description '-' 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'只有转换。

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

    宽度

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

    精确

    对于常规参数类型,precision是要写入输出的最大字符数。

    对于浮点转换'a''A''e''E' ,和'f'精度的小数点后的位数。 如果转换为'g''G' ,则精度是舍入后得到的幅度中的总位数。

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

    论证索引

    参数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

    如果格式说明符包含具有无效值的宽度或精度或者不支持, 则将分别抛出IllegalFormatWidthExceptionIllegalFormatPrecisionException

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

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

    对于A类普通性格数字小积分日期/时间转换,除非另有规定,如果参数argnull ,那么结果是“ null ”。

    通过一个大写字符标记转换(即'B''H''S''C''X''E''G''A' ,和'T' )是相同的那些相应的小写转换字符除了将结果转换成上根据现行规则Locale的情况 如果没有指定显式语言环境,无论是在构造实例还是作为其方法调用的参数,都使用default locale

    General

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

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

    If the argument is null, then the result is "false". If the argument is a boolean or Boolean, then the result is the string returned by String.valueOf(). Otherwise, the result is "true".

    If the '#' flag is given, then a FormatFlagsConversionMismatchException will be thrown.

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

    The result is obtained by invoking Integer.toHexString(arg.hashCode()).

    If the '#' flag is given, then a FormatFlagsConversionMismatchException will be thrown.

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

    If the argument implements Formattable, then its formatTo method is invoked. Otherwise, the result is obtained by invoking the argument's toString() method.

    If the '#' flag is given and the argument is not a Formattable , then a FormatFlagsConversionMismatchException will be thrown.

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

    以下flags适用于一般转换:

    dFlags '-' '\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

    此转换可应用于charCharacter 它也可以被施加到类型byteByteshort ,和ShortintIntegerCharacter.isValidCodePoint(int)返回true 如果它返回false那么将抛出IllegalFormatCodePointException charConv '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.

    If the '#' flag is given, then a FormatFlagsConversionMismatchException will be thrown.

    '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. 字符串中的每个数字字符d由相对于当前语言环境zero digit z计算的特定于语言环境的数字替换 ; 那是d - '0' + z
    2. 如果存在小数分隔符,则替换特定语言环境的decimal separator
    3. 如果',''\u002c'flag给出,那么语言环境的特定grouping separator通过在由区域设置的规定的时间间隔扫描所述字符串从至少显著到最显著位数的整数部分和插入的隔板插入grouping size
    4. 如果给出了'0'标志,则在符号字符(如果有)和第一个非零数字之前插入特定于语言环境的zero digits ,直到字符串的长度等于请求的字段宽度。
    5. 如果该值为负且'('标志被给出,那么'(''\u0028' )被前置和')''\u0029' )将被附加。
    6. 如果该值为负(或浮点负零)并且未给出'('标志,则前置'-''\u002d' )。
    7. 如果给出了'+'标志并且该值为正或零(或浮点正零),那么将添加'+''\u002b' )。

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

    Byte, Short, Integer, and Long

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

    IntConv '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 a FormatFlagsConversionMismatchException will 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 n is the number of bits in the type as returned by the static SIZE field 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 a FormatFlagsConversionMismatchException will 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 n is the number of bits in the type as returned by the static SIZE field 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 a FormatFlagsConversionMismatchException will 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 'a' - 'f' ('\u0061' - '\u0066').

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

    如果未给出'-'标志,则空格填充将在符号之前出现。

    以下flags适用于数字积分转换:

    intFlags '+' '\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 an IllegalFormatFlagsException will 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 an IllegalFormatFlagsException will be thrown.

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

    If both the '-' and '0' flags are given then an IllegalFormatFlagsException will be thrown.

    ',' '\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右对齐
    • 负数以'-''\u002d'
    • 正数和零不包括符号或额外的前导空格
    • 不包括分组分隔符

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

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

    BigInteger

    以下转换可能适用于BigInteger

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

    If the '#' flag is given FormatFlagsConversionMismatchException will be thrown.

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

    If x is negative then the result will be a signed value beginning with '-' ('\u002d'). Signed output is allowed for this type because unlike the primitive types it is not possible to create an unsigned equivalent without assuming an explicit data-type size.

    If x is positive or zero and the '+' flag is given then the result will begin with '+' ('\u002b').

    If the '#' flag is given then the output will always begin with '0' prefix.

    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 the ',' flag is given then a FormatFlagsConversionMismatchException will be thrown.

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

    If x is negative then the result will be a signed value beginning with '-' ('\u002d'). Signed output is allowed for this type because unlike the primitive types it is not possible to create an unsigned equivalent without assuming an explicit data-type size.

    If x is positive or zero and the '+' flag is given then the result will begin with '+' ('\u002b').

    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 the ',' flag is given then a FormatFlagsConversionMismatchException will 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 'a' - 'f' ('\u0061' - '\u0066').

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

    如果给出了'0'标志且值为负,则在符号后将出现零填充。

    如果未给出'-'标志,则空格填充将在符号前发生。

    为字节,短,整数和长定义的所有flags均适用。 没有给出标志时的default behavior与Byte,Short,Integer和Long相同。

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

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

    Float and Double

    以下转换可以应用于floatFloatdoubleDouble

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

    The formatting of the magnitude m depends upon its value.

    If m is NaN or infinite, the literal strings "NaN" or "Infinity", respectively, will be output. These values are not localized.

    If m is positive-zero or negative-zero, then the exponent will be "+00".

    Otherwise, 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.

    Let n be the unique integer such that 10n <= m < 10n+1; then let a be the mathematically exact quotient of m and 10n so that 1 <= a < 10. The magnitude is then represented as the integer part of a, as a single decimal digit, followed by the decimal separator followed by decimal digits representing the fractional part of a, followed by the exponent symbol 'e' ('\u0065'), followed by the sign of the exponent, followed by a representation of n as a decimal integer, as produced by the method Long.toString(long, int), and zero-padded to include at least two digits.

    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 by Float.toString(float) or Double.toString(double) respectively, then the value will be rounded using the round half up algorithm. Otherwise, zeros may be appended to reach the precision. For a canonical representation of the value, use Float.toString(float) or Double.toString(double) as appropriate.

    If the ',' flag is given, then an FormatFlagsConversionMismatchException will be thrown.

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

    After rounding for the precision, the formatting of the resulting magnitude m depends on its value.

    If m is greater than or equal to 10-4 but less than 10precision then it is represented in decimal format.

    If m is less than 10-4 or greater than or equal to 10precision, then it is represented in computerized scientific notation.

    The total number of significant digits in m is equal to the precision. If the precision is not specified, then the default value is 6. If the precision is 0, then it is taken to be 1.

    If the '#' flag is given then an FormatFlagsConversionMismatchException will be thrown.

    'G' '\u0047' The upper-case variant of 'g'. '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 by Float.toString(float) or Double.toString(double) respectively, then the value will be rounded using the round half up algorithm. Otherwise, zeros may be appended to reach the precision. For a canonical representation of the value, use Float.toString(float) or Double.toString(double) as appropriate.

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

    The result is a string that represents the sign and magnitude (absolute value) of the argument x.

    If x is negative or a negative-zero value then the result will begin with '-' ('\u002d').

    If x is positive or a positive-zero value and the '+' flag is given then the result will begin with '+' ('\u002b').

    The formatting of the magnitude m depends upon its value.

    • 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 the precision is specified, the value is rounded to the given number of hexadecimal digits.
    • If m is a double value with a subnormal representation then, unless the precision is specified to be in the range 1 through 12, inclusive, the significand is represented by the characters '0x0.' followed by the hexadecimal representation of the rest of the significand as a fraction, and the exponent represented by 'p-1022'. If the precision is in the interval [1, 12], the subnormal value is normalized such that it begins with the characters '0x1.', rounded to the number of hexadecimal digits of precision, and the exponent adjusted accordingly. Note that there must be at least one nonzero digit in a subnormal significand.

    If the '(' or ',' flags are given, then a FormatFlagsConversionMismatchException will be thrown.

    '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右对齐
    • 负数以'-'
    • 正数和正零不包括符号或额外的前导空格
    • 不包括分组分隔符
    • 小数分隔符仅在其后跟一个数字时出现

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

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

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

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

    BigDecimal

    可以应用以下转换BigDecimal

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

    The formatting of the magnitude m depends upon its value.

    If m is positive-zero or negative-zero, then the exponent will be "+00".

    Otherwise, 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.

    Let n be the unique integer such that 10n <= m < 10n+1; then let a be the mathematically exact quotient of m and 10n so that 1 <= a < 10. The magnitude is then represented as the integer part of a, as a single decimal digit, followed by the decimal separator followed by decimal digits representing the fractional part of a, followed by the exponent symbol 'e' ('\u0065'), followed by the sign of the exponent, followed by a representation of n as a decimal integer, as produced by the method Long.toString(long, int), and zero-padded to include at least two digits.

    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 to the right of the decimal point then the value will be rounded using the round half up algorithm. Otherwise, zeros may be appended to reach the precision. For a canonical representation of the value, use BigDecimal.toString().

    If the ',' flag is given, then an FormatFlagsConversionMismatchException will be thrown.

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

    After rounding for the precision, the formatting of the resulting magnitude m depends on its value.

    If m is greater than or equal to 10-4 but less than 10precision then it is represented in decimal format.

    If m is less than 10-4 or greater than or equal to 10precision, then it is represented in computerized scientific notation.

    The total number of significant digits in m is equal to the precision. If the precision is not specified, then the default value is 6. If the precision is 0, then it is taken to be 1.

    If the '#' flag is given then an FormatFlagsConversionMismatchException will be thrown.

    'G' '\u0047' The upper-case variant of 'g'. '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.

    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 to the right of the decimal point then the value will be rounded using the round half up algorithm. Otherwise, zeros may be appended to reach the precision. For a canonical representation of the value, use BigDecimal.toString().

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

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

    没有给出标志的default behavior与Float和Double相同。

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

    Date/Time

    这种转换可以应用于longLongCalendarDateTemporalAccessor

    DTConv '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' )。

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

    time '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.

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

    date '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.

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

    composites '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则输出将用空格( '\u0020' )填充,直到总字符数等于宽度。 默认情况下,填充位于左侧。 如果给出了'-'标志,那么填充将在右侧。 如果未指定宽度,则没有最小值。

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

    Percent

    转换与任何参数都不对应。

    DTConv '%' 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 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. If width is not specified then just the '%' is output.

    The '-' flag defined for General conversions applies. If any other flags are provided, then a FormatFlagsConversionMismatchException will be thrown.

    The precision is not applicable. If the precision is specified an IllegalFormatPrecisionException will be thrown.

    Line Separator

    转换与任何参数都不对应。

    DTConv 'n' the platform-specific line separator as returned by System.lineSeparator().

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

    Argument Index

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

    • 当格式说明符包含参数索引时,使用显式索引 参数index是一个十进制整数,表示参数列表中参数的位置。 第一个参数由“ 1$ ”引用,第二个参数由“ 2$ ”引用,等等。参数可以多次引用。

      例如:

         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"
       
    • 当格式说明符包含'<''\u003c' )标志时,将使用相对索引 ,该标志会导致重复使用前一格式说明符的参数。 如果没有先前的参数,则抛出MissingFormatArgumentException
          formatter.format("%s %s %<s %<s", "a", "b", "c", "d")
          // -> "a b b b"
          // "c" and "d" are ignored because they are not referenced
       
    • 当格式说明符既不包含参数索引也不包含'<'标志时,使用普通索引 使用普通索引的每个格式说明符都被赋予一个顺序隐式索引到参数列表中,该索引独立于显式或相对索引使用的索引。
         formatter.format("%s %s %s %s", "a", "b", "c", "d")
         // -> "a b c d"
       

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

       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

    从以下版本开始:
    1.5
    • 构造方法详细信息

      • Formatter

        public Formatter()
        构造一个新的格式化程序。

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

      • Formatter

        public Formatter​(Appendable a)
        构造具有指定目标的新格式化程序。

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

        参数
        a - 格式化输出的目标。 如果anull那么将创建一个StringBuilder
      • Formatter

        public Formatter​(Locale l)
        使用指定的语言环境构造一个新的格式化程序。

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

        参数
        l - 格式化期间应用的locale 如果lnull则不应用本地化。
      • Formatter

        public Formatter​(Appendable a,
                         Locale l)
        使用指定的目标和语言环境构造一个新的格式化程序。
        参数
        a - 格式化输出的目标。 如果anull那么将创建一个StringBuilder
        l - 格式化期间应用的locale 如果lnull则不应用本地化。
      • Formatter

        public Formatter​(String fileName)
                  throws FileNotFoundException
        使用指定的文件名构造一个新的格式化程序。

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

        对于此Java虚拟机实例,使用的语言环境是447327966372,用于formatting

        参数
        fileName - 要用作此格式化程序的目标的文件的名称。 如果该文件存在,那么它将被截断为零大小; 否则,将创建一个新文件。 输出将写入文件并进行缓冲。
        异常
        SecurityException - 如果存在安全管理器且 checkWrite(fileName)拒绝对文件的写访问权
        FileNotFoundException - 如果给定的文件名不表示现有的可写常规文件,并且无法创建该名称的新常规文件,或者在打开或创建文件时发生其他错误
      • Formatter

        public Formatter​(String fileName,
                         String csn,
                         Locale l)
                  throws FileNotFoundException,
                         UnsupportedEncodingException
        使用指定的文件名,charset和locale构造一个新的格式化程序。
        参数
        fileName - 要用作此格式化程序的目标的文件的名称。 如果该文件存在,那么它将被截断为零大小; 否则,将创建一个新文件。 输出将写入文件并进行缓冲。
        csn - 支持的charset的名称
        l - 格式化期间应用的locale 如果lnull则不应用本地化。
        异常
        FileNotFoundException - 如果给定的文件名不表示现有的可写常规文件,并且无法创建该名称的新常规文件,或者在打开或创建文件时发生其他错误
        SecurityException - 如果存在安全管理器且 checkWrite(fileName)拒绝对文件的写访问权
        UnsupportedEncodingException - 如果不支持指定的字符集
      • Formatter

        public Formatter​(String fileName,
                         Charset charset,
                         Locale l)
                  throws IOException
        使用指定的文件名,charset和locale构造一个新的格式化程序。
        参数
        fileName - 要用作此格式化程序的目标的文件的名称。 如果该文件存在,那么它将被截断为零大小; 否则,将创建一个新文件。 输出将写入文件并进行缓冲。
        charset - A charset
        l - 格式化期间应用的locale 如果lnull则不应用本地化。
        异常
        IOException - 如果在打开或创建文件时发生I / O错误
        SecurityException - 如果存在安全管理器且 checkWrite(fileName)拒绝对文件的写访问权
        NullPointerException - 如果 fileNamecharsetnull
      • Formatter

        public Formatter​(File file)
                  throws FileNotFoundException
        使用指定的文件构造一个新的格式化程序。

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

        对于此Java虚拟机实例,使用的语言环境是default localeformatting)

        参数
        file - 用作此格式化程序的目标的文件。 如果该文件存在,那么它将被截断为零大小; 否则,将创建一个新文件。 输出将写入文件并进行缓冲。
        异常
        SecurityException - 如果存在安全管理器且 checkWrite(file.getPath())拒绝对文件的写访问权
        FileNotFoundException - 如果给定的文件对象不表示现有的可写常规文件,并且无法创建该名称的新常规文件,或者在打开或创建文件时发生其他错误
      • Formatter

        public Formatter​(File file,
                         String csn,
                         Locale l)
                  throws FileNotFoundException,
                         UnsupportedEncodingException
        使用指定的文件,charset和locale构造一个新的格式化程序。
        参数
        file - 用作此格式化程序的目标的文件。 如果该文件存在,那么它将被截断为零大小; 否则,将创建一个新文件。 输出将写入文件并进行缓冲。
        csn - 支持的charset的名称
        l - 格式化期间应用的locale 如果lnull则不应用本地化。
        异常
        FileNotFoundException - 如果给定的文件对象不表示现有的可写常规文件,并且无法创建该名称的新常规文件,或者在打开或创建文件时发生其他错误
        SecurityException - 如果存在安全管理器且 checkWrite(file.getPath())拒绝对该文件的写访问权
        UnsupportedEncodingException - 如果不支持指定的charset
      • Formatter

        public Formatter​(File file,
                         Charset charset,
                         Locale l)
                  throws IOException
        使用指定的文件,charset和locale构造一个新的格式化程序。
        参数
        file - 用作此格式化程序的目标的文件。 如果该文件存在,那么它将被截断为零大小; 否则,将创建一个新文件。 输出将写入文件并进行缓冲。
        charset - A charset
        l - 格式化时应用的locale 如果lnull则不应用本地化。
        异常
        IOException - 如果在打开或创建文件时发生I / O错误
        SecurityException - 如果存在安全管理器且 checkWrite(file.getPath())拒绝对该文件的写访问权
        NullPointerException - 如果 filecharsetnull
      • Formatter

        public Formatter​(PrintStream ps)
        使用指定的打印流构造一个新的格式化程序。

        对于此Java虚拟机实例,使用的语言环境是default localeformatting)

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

        参数
        ps - 用作此格式化程序目标的流。
      • Formatter

        public Formatter​(OutputStream os)
        使用指定的输出流构造一个新的格式化程序。

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

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

        参数
        os - 用作此格式化程序的目标的输出流。 输出将被缓冲。
      • Formatter

        public Formatter​(OutputStream os,
                         Charset charset,
                         Locale l)
        使用指定的输出流,字符集和语言环境构造一个新的格式化程序。
        参数
        os - 用作此格式化程序目标的输出流。 输出将被缓冲。
        charset - A charset
        l - 格式化期间应用的locale 如果lnull则不应用本地化。
        异常
        NullPointerException - 如果 oscharsetnull
    • 方法详细信息

      • locale

        public Locale locale()
        返回由此formatter构造设置的语言环境。

        具有locale参数的此对象的format方法不会更改此值。

        结果
        null如果未应用本地化,则为区域设置
        异常
        FormatterClosedException - 如果已通过调用其 close()方法关闭此格式化程序
      • toString

        public 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() 

        根据toString规范 ,返回的字符串可能包含也可能不包含写入目标的字符。 例如,缓冲区通常在toString()返回其内容,但由于数据被丢弃,因此流不能。

        重写:
        toString在类 Object
        结果
        在输出的目标上调用 toString()的结果
        异常
        FormatterClosedException - 如果已通过调用其 close()方法关闭此格式化程序
      • flush

        public void flush()
        刷新此格式化程序。 如果目标实现Flushable接口,则将调用其flush方法。

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

        Specified by:
        flush在接口 Flushable
        异常
        FormatterClosedException - 如果已通过调用其 close()方法关闭此格式化程序
      • close

        public void close()
        关闭此格式化程序。 如果目标实现Closeable接口,则将调用其close方法。

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

        在此格式化程序关闭后尝试调用除ioException()之外的任何方法将导致FormatterClosedException

        Specified by:
        close在界面 AutoCloseable
        Specified by:
        close在界面 Closeable
      • ioException

        public IOException ioException()
        返回此格式化程序IOException最后抛出的IOException

        如果目标的append()方法永远不会抛出IOException ,则此方法将始终返回null

        结果
        如果不存在此类异常,则Appendable或 null抛出的最后一个异常。
      • format

        public Formatter format​(String format,
                                Object... args)
        使用指定的格式字符串和参数将格式化的字符串写入此对象的目标。 使用的语言环境是在构造此格式化程序期间定义的语言环境。
        参数
        format -如在描述的格式字符串 Format string syntax
        args - 格式字符串中格式说明符引用的参数。 如果参数多于格式说明符,则忽略额外参数。 参数的最大数量受The Java™ Virtual Machine Specification定义的Java数组的最大维数限制。
        结果
        这个格式化程序
        异常
        IllegalFormatException - 如果格式字符串包含非法语法,格式说明符与给定参数不兼容,给定格式字符串的参数不足或其他非法条件。 有关所有可能的格式错误的说明,请参阅formatter类规范的Details部分。
        FormatterClosedException - 如果已通过调用其 close()方法关闭此格式化程序
      • format

        public Formatter format​(Locale l,
                                String format,
                                Object... args)
        使用指定的语言环境,格式字符串和参数将格式化的字符串写入此对象的目标。
        参数
        l - 格式化期间应用的locale 如果lnull则不应用本地化。 这不会更改此对象在构造期间设置的区域设置。
        format -如在描述的格式字符串 Format string syntax
        args - 格式字符串中格式说明符引用的参数。 如果参数多于格式说明符,则忽略额外参数。 参数的最大数量受The Java™ Virtual Machine Specification定义的Java数组的最大维数限制。
        结果
        这个格式化程序
        异常
        IllegalFormatException - 如果格式字符串包含非法语法,格式说明符与给定参数不兼容,给定格式字符串的参数不足或其他非法条件。 有关所有可能的格式错误的说明,请参阅formatter类规范的Details部分。
        FormatterClosedException - 如果已通过调用其 close()方法关闭此格式化程序