Module  java.base
软件包  java.util

Class Formatter

  • All Implemented Interfaces:
    CloseableFlushableAutoCloseable


    public final class Formatter
    extends Object
    implements Closeable, Flushable
    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$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$ ”等。

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

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

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

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

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

      argument_indexflagswidth的可选参数如上所述。

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

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

      可选标志宽度如上定义。

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

    转换

    转换分为以下几类:

    1. 一般 - 可以应用于任何参数类型
    2. 字符 -可以被施加到其代表的Unicode字符基本类型: charCharacterbyteByteshort ,和Short 这种转换也可以被施加到所述类型intIntegerCharacter.isValidCodePoint(int)返回true
    3. 数字
      1. 积分 -可应用于Java的整数类型: byteByteshortShortintIntegerlongLong ,并BigInteger (但不char或者Character
      2. 浮点 -可用于Java的浮点类型: floatFloatdoubleDouble ,并BigDecimal
    4. 日期/时间 -可以被施加到Java类型,其能够编码的日期或时间的: longLongCalendarDateTemporalAccessor
    5. 百分比 - 产生字面值'%''\u0025'
    6. 线分离器 - 生产平台专用线分离器

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

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

      out.toUpperCase(Locale.getDefault(Locale.Category.FORMAT)) 
    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'只有转换。

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

    宽度

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

    精确

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

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

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

    参数指数

    参数index是一个十进制整数,表示参数在参数列表中的位置。 第一个参数为“ 1$ ”,第二个为“ 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

    对于类别GeneralCharacterNumbericIntegralDate / Time转换,除非另有说明,如果参数argnull ,则结果为“ null ”。

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

      out.toUpperCase(Locale.getDefault(Locale.Category.FORMAT)) 

    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 separator18
    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 ,默认格式如下:

    • 输出在widthwidth
    • 负数以'-''\u002d' )开头
    • 正数和零不包括符号或额外的前导空间
    • 不包括分组分隔符

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

    精度不适用。 如果指定精度,则抛出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当没有标志被赋予与字节,短,整数和长度相同。

    width的规格与字节,短,整数和长度相同。

    精度不适用。 如果指定精度,则抛出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').

    所有flags定义为字节,短,整数和长度适用。

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

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

    • 输出在widthwidth
    • 负数以'-'
    • 正数和正零不包括符号或额外的前导空间
    • 不包括分组分隔符
    • 小数分隔符仅在数字跟随时才会出现

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

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

    如果转换为'g''G' ,则精度是四舍五入后产生的大小的有效数字的总数。 如果未指定精度,则默认值为6 如果精度为01

    如果转换为'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().

    所有flags为Byte,Short,Integer和Long定义。

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

    default behavior当没有标志被赋予与浮动和双重相同。

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

    精度不适用。 如果指定精度,则抛出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虚拟机实例的formattingdefault locale

      • 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
        构造具有指定文件名的新格式化程序。

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

        使用的语言环境是default localeformatting Java虚拟机实例。

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

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

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

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

        所使用的语言环境是这个Java虚拟机实例的default locale formatting

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

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

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

        所使用的语言环境是这个Java虚拟机实例的formattingdefault locale

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

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

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

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

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

        参数
        os - 用作此格式化程序的目标的输出流。 输出将被缓冲。
    • 方法详细信息

      • locale

        public Locale locale​()
        返回通过构建此格式化程序设置的区域设置。

        具有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() 

        取决于toStringtoString的规格,返回的字符串可能包含或不包含写入目的地的字符。 例如,缓冲区通常在toString()返回其内容,但是由于数据被丢弃,流不能。

        重写:
        toStringObject
        结果
        调用 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最后通过此格式的抛出Appendable

        如果目的地的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 - 如果格式字符串包含非法语法,则与给定参数不兼容的格式说明符,给定格式字符串的参数不足或其他非法条件。 有关所有可能的格式化错误的规范,请参阅格式化程序类规范的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 - 如果格式字符串包含非法语法,则与给定参数不兼容的格式说明符,给定格式字符串的参数不足或其他非法条件。 有关所有可能的格式化错误的规范,请参阅格式化程序类规范的Details部分。
        FormatterClosedException - 如果该格式化程序通过调用其 close()方法已关闭