Translation_java_Formatter

Python+Tkinter开发轻量级桌面天气应用实战 桌面应用开发是提升工作效率的重要技术方向,Python凭借其简洁语法和丰富生态成为快速开发的首选语言。Tkinter作为Python内置GUI库,具有零依赖、跨平台和低资源占用的特点,特别适合开发轻量级工具类应用。通过调用天气API获取实时数据,结合matplotlib实现可视化展示,开发者可以构建功能完善的桌面程序。本文以天气应用为例,详细解析了从API对接、数据可视化到内存优化的全流程实践,其中彩云天气API的分钟级降水预报和Tkinter的悬浮窗实现是技术亮点。这类工具在个人效率管理、环境监测等场景具 阅读详情

java.util
Class Formatter

java.lang.Object extended by java.util.Formatter
All Implemented Interfaces:
Closeable, Flushable

public final class Formatter
extends Objectimplements Closeable, Flushable

An interpreter(转意) for printf-style format strings. This class provides support(支持) forlayout(布局) justification(正规的) and alignment(排列), common(普遍的) formats for numeric, string, and date/time data, and locale-specific(特殊地方) output. Common Java types such as byte,BigDecimal, and Calendar(日期) are supported. Limited(限制) formatting customization(自定义) forarbitrary(任意) user types is provided through the Formattable interface.


一种转义字符传的格式,这个类提供了布局和排列,普遍的格式数字,字符串和日期时间; 
然后输出在特殊的地方。通常java的类型像字节, BigDecimal ,和日期是支持的,
自定义格式是被限制的,任何使用类型通过实现formattable接口被支持的
 

Formatters are not necessarily safe for multithreaded access. Thread safety is optional(可选择的) and is the responsibility(可靠的) of users of methods in this class.


格式是不需要多线程安全的访问,线程安全是可选择的,和使用的方法是可靠的在这个类中

Formatted printing for the Java language is heavily inspired(受..影响) by C's printf. Although the format strings are similar to C, some customizations(自定义) have been made to accommodate(适应) the Java language and exploit(开发) some of its features(特征). Also, Java formatting is more strict than C's; for example, if a conversion is incompatible(不符合) with a flag(标志), an exception will be thrown. In C inapplicable flags are silently ignored. The format strings arethus(结果) intended(打算) to be recognizable(可认的) to C programmers(程序员) but not necessarilycompletely(完全的) compatible(兼容的) with those in C.

Java语言的格式打印受C的printf,尽管格式字符传是同C相同的,但是为了适应
Java语言已经作出了一些自定义改变,和开发了一些自己的特征。Java格式化严格比C;
例如,假如一个转换是不符合,例题将会被抛出。在C中是被忽略的。
Java格式字符给C程序员认识的,但不完全兼容给C用

Examples of expected usage:

StringBuilder sb = new StringBuilder(); // Send all output to the Appendable object sb Formatter formatter = new Formatter(sb, Locale.US); // Explicit(详细的) argument(参数) indices may be used to re-order output. formatter.format("%4$2s %3$2s %2$2s %1$2s", "a", "b", "c", "d") // -> " d c b a" // 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)"

Convenience(便利) methods for common(普遍的) formatting requests exist as illustrated(说明) by the following invocations:

一些比较便利常用的格式化,都被下面说明了

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

Like C's sprintf(3), Strings may be formatted using the static method 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

This specification(规定) is divided(分) into two sections(部分). The first section, Summary(总结), covers the basic formatting concepts(概念). This section is intended(为..打算) for users who want to get started quickly and are familiar(熟悉) with formatted printing in other programming languages. The second section, Details, covers the specific implementation(执行操作) details. It is intended for users who want more precise(规格) specification of formatting behavior(作用).

它的规定分为两部分,第一部分总结包含了基本的格式概念。这部分的目的是为用户快速开始,
和熟悉格式化输出在其他编程语言中;
这第二部分,包含它的详细执行,它的目的是为了让用户得到更多关于格式化规范

Summary

This section is intended(目的) to provide a brief(短暂的) overview(概述) of formatting concepts(概念). For precise behavioral details, refer to the Details section.

这章的目的是提供一个简短的格式化概念,参考详细资料

Format String Syntax(语法)

Every method which produces(产生) formatted output  requires(需要) a format string and an argument list. The format string is a String which may contain fixed text and one or more embedded(嵌入) format specifiers(区分符). Consider the following example:

每个格式化输出的方法需要一个格式化字符串和一个对象列表

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.

这格式化字符串是第一个对象给这格式方法,它包含了三个格式化区分符: %1$tm, %1$te,和 %1$tY ;
它表示那个参数可以被修改和它们被嵌入到这文本中,这剩余的部分是固定的
包含: Dukes Birthday 和任何空格或标点符号,参数列表由传过来的方法参数决定在格式化字符后。
在上面的例子中,
 
  • The format specifiers for general, character, and numeric types have the following syntax:
    %[argument_index$][flags][width][.precision]conversion

    The optional argument_index is a decimal integer indicating(标志) the position(位置) of the argument in the argument list. The first argument is referenced by "1$", the second by "2$", etc.

    这个参数索引是一个十进制的整数,它标志在参数列表中的位置。这第一个引用的是‘1$;
  • 第二个‘2$’
  •  

    The optional(选择) flags is a set of characters that modify the output format. The set ofvalid(有效的) flags depends on the conversion.

    选择标志的是一堆字符集,它被格式化修改输出的;这些有效的标志决定了转换

    The optional width is a non-negative(非负) decimal integer indicating(表示) the minimum number of characters to be written to the output.

    它的宽度是一个非负数的十进制的整数,表示最小写入到输出的

    The optional precision is a non-negative decimal integer usually used to restrict(限制) the number of characters. The specific behavior(作用) depends on the conversion.

    The required conversion is a character indicating how the argument should be formatted. The set of valid conversions for a given argument depends on the argument's data type.

  • The format specifiers for types which are used to represents dates and times have the following syntax:

  •  
    %[argument_index$][flags][width]conversion

    The optional argument_index, flags and width are defined as above.

    The required conversion is a two character sequence. The first character is 't' or 'T'. The second character indicates the format to be used. These characters are similar to but not completely identical to those defined by GNU date and POSIX strftime(3c).

  • The format specifiers which do not correspond to arguments have the following syntax:
    %[flags][width]conversion

    The optional flags and width is defined as above.

    The required conversion is a character indicating content to be inserted in the output.

Conversions

Conversions are divided into the following categories:

  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 intand Integer when Character.isValidCodePoint(int) returns true
  3. Numeric
    1. Integral - may be applied to Java integral types: byte, Byte, short, Short, int andInteger, 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

The following table summarizes the supported conversions. Conversions denoted by an upper-case character (i.e. 'B', 'H', 'S', 'C', 'X', 'E', 'G', 'A', and 'T') are the same as those for the corresponding lower-case conversion characters except that the result is converted to upper case according to the rules of the prevailing Locale. The result is equivalent to the following invocation of String.toUpperCase()

out.toUpperCase()
ConversionArgument CategoryDescription
'b', 'B' generalIf the argument arg is null, then the result is "false". If arg is aboolean or Boolean, then the result is the string returned byString.valueOf(). Otherwise, the result is "true".
'h', 'H' generalIf the argument arg is null, then the result is "null". Otherwise, the result is obtained by invoking Integer.toHexString(arg.hashCode()).
's', 'S' generalIf the argument arg is null, then the result is "null". If argimplements Formattable, then arg.formatTo is invoked. Otherwise, the result is obtained by invoking arg.toString().
'c', 'C' characterThe result is a Unicode character
'd' integralThe result is formatted as a decimal integer
'o' integralThe result is formatted as an octal integer
'x', 'X' integralThe result is formatted as a hexadecimal integer
'e', 'E' floating pointThe result is formatted as a decimal number in computerized scientific notation
'f' floating pointThe result is formatted as a decimal number
'g', 'G' floating pointThe result is formatted using computerized scientific notation or decimal format, depending on the precision and the value after rounding.
'a', 'A' floating pointThe result is formatted as a hexadecimal floating-point number with a significand and an exponent
't', 'T' date/timePrefix for date and time conversion characters. See Date/Time Conversions.
'%' percentThe result is a literal '%' ('\u0025')
'n' line separatorThe result is the platform-specific line separator

Any characters not explicitly defined as conversions are illegal and are reserved for future extensions.

Date/Time Conversions

The following date and time conversion suffix characters are defined for the 't' and 'T'conversions. The types are similar to but not completely identical to those defined by GNU dateand POSIX strftime(3c). Additional conversion types are provided to access Java-specific functionality (e.g. 'L' for milliseconds within the second).

The following conversion characters are used for formatting times:

'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.
'Z'A string representing the abbreviation for the time zone. 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.

The following conversion characters are used for formatting dates:

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

The following conversion characters are used for formatting common date/time compositions.

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

Any characters not explicitly defined as date/time conversion suffixes are illegal and are reserved for future extensions.

Flags

The following table summarizes the supported flags. y means the flag is supported for the indicated argument types.

FlagGeneralCharacterIntegralFloating PointDate/TimeDescription
'-' y y y y yThe 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 Depends on the definition of Formattable.

2 For 'd' conversion only.

3 For 'o', 'x', and 'X' conversions only.

4 For 'd', 'o', 'x', and 'X' conversions applied to BigInteger or 'd' applied to byte, Byte, short,Short, int and Integer, long, and Long.

5 For 'e', 'E', 'f', 'g', and 'G' conversions only.

Any characters not explicitly defined as flags are illegal and are reserved for future extensions.

Width

The width is the minimum number of characters to be written to the output. For the line separator conversion, width is not applicable; if it is provided, an exception will be thrown.

Precision

For general argument types, the precision is the maximum number of characters to be written to the output.

For the floating-point conversions 'e', 'E', and 'f' the precision is the number of digits after the decimal separator. If the conversion is 'g' or 'G', then the precision is the total number of digits in the resulting magnitude after rounding. If the conversion is 'a' or 'A', then the precision must not be specified.

For character, integral, and date/time argument types and the percent and line separator conversions, the precision is not applicable; if a precision is provided, an exception will be thrown.

Argument Index

The argument index is a decimal integer indicating the position of the argument in the argument list. The first argument is referenced by "1$", the second by "2$", etc.

Another way to reference arguments by position is to use the '<' ('\u003c') flag, which causes the argument for the previous format specifier to be re-used. For example, the following two statements would produce identical strings:

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

Details

This section is intended to provide behavioral details for formatting, including conditions and exceptions, supported data types, localization, and interactions between flags, conversions, and data types. For an overview of formatting concepts, refer to the Summary

Any characters not explicitly defined as conversions, date/time conversion suffixes, or flags are illegal and are reserved for future extensions. Use of such a character in a format string will cause an UnknownFormatConversionException or UnknownFormatFlagsException to be thrown.

If the format specifier contains a width or precision with an invalid value or which is otherwise unsupported, then a IllegalFormatWidthException or IllegalFormatPrecisionException respectively will be thrown.

If a format specifier contains a conversion character that is not applicable to the corresponding argument, then an IllegalFormatConversionException will be thrown.

All specified exceptions may be thrown by any of the format methods of Formatter as well as by anyformat convenience methods such as String.format and PrintStream.printf.

Conversions denoted by an upper-case character (i.e. 'B', 'H', 'S', 'C', 'X', 'E', 'G', 'A', and'T') are the same as those for the corresponding lower-case conversion characters except that the result is converted to upper case according to the rules of the prevailing Locale. The result is equivalent to the following invocation of String.toUpperCase()

out.toUpperCase()
General

The following general conversions may be applied to any argument type:

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

If the argument, arg is null, then the result is "null". Otherwise, 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 is null, then the result is "null". If the argument implementsFormattable, 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 aFormatFlagsConversionMismatchException will be thrown.

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

The following flags apply to general conversions:

'-' '\u002d'Left justifies the output. Spaces ('\u0020') will be added at the end of the converted value as required to fill the minimum width of the field. If the width is not provided, then a 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.

The width is the minimum number of characters to be written to the output. If the length of the converted value is less than the width then the output will be padded by '  ' (\u0020') until the total number of characters equals the width. The padding is on the left by default. If the '-'flag is given, then the padding will be on the right. If the width is not specified then there is no minimum.

The precision is the maximum number of characters to be written to the output. The precision is applied before the width, thus the output will be truncated to precision characters even if the width is greater than the precision. If the precision is not specified then there is no explicit limit on the number of characters.

Character
This conversion may be applied to char and Character. It may also be applied to the types byte,Byte, short, and Short, int and Integer when Character.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.

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

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

The '-' flag defined for General conversions applies. If the '#' flag is given, then aFormatFlagsConversionMismatchException will be thrown.

The width is defined as for General conversions.

The precision is not applicable. If the precision is specified then anIllegalFormatPrecisionException will be thrown.

Numeric

Numeric conversions are divided into the following categories:

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

Numeric types will be formatted according to the following algorithm:

Number Localization Algorithm

After digits are obtained for the integer part, fractional part, and exponent (as appropriate for the data type), the following transformation is applied:

  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.

If the value is NaN or positive infinity the literal strings "NaN" or "Infinity" respectively, will be output. If the value is negative infinity, then the output will be "(Infinity)" if the '('flag is given otherwise the output will be "-Infinity". These values are not localized.

Byte, Short, Integer, and Long

The following conversions may be applied to byte, Byte, short, Short, int and Integer, long, andLong.

'd' '\u0054'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 2nto the value where n is the number of bits in the type as returned by the staticSIZE 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 aFormatFlagsConversionMismatchException 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 2nto the value where n is the number of bits in the type as returned by the staticSIZE 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 aFormatFlagsConversionMismatchException 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').

If the conversion is 'o', 'x', or 'X' and both the '#' and the '0' flags are given, then result will contain the radix indicator ('0' for octal and "0x" or "0X" for hexadecimal), some number of zeros (based on the width), and the value.

If the '-' flag is not given, then the space padding will occur before the sign.

The following flags apply to numeric integral conversions:

'+' '\u002b'Requires the output to include a positive sign for all positive numbers. If this flag is not given then only negative values will include a sign.

If both the '+' and '  ' flags are given then 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.

If no flags are given the default formatting is as follows:

  • The output is right-justified within the width
  • Negative numbers begin with a '-' ('\u002d')
  • Positive numbers and zero do not include a sign or extra leading space
  • No grouping separators are included

The width is the minimum number of characters to be written to the output. This includes any signs, digits, grouping separators, radix indicator, and parentheses. If the length of the converted value is less than the width then the output will be padded by spaces ('\u0020') until the total number of characters equals width. The padding is on the left by default. If '-' flag is given then the padding will be on the right. If width is not specified then there is no minimum.

The precision is not applicable. If precision is specified then an IllegalFormatPrecisionExceptionwill be thrown.

BigInteger

The following conversions may be applied to BigInteger.

'd' '\u0054'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').

If the conversion is 'o', 'x', or 'X' and both the '#' and the '0' flags are given, then result will contain the base indicator ('0' for octal and "0x" or "0X" for hexadecimal), some number of zeros (based on the width), and the value.

If the '0' flag is given and the value is negative, then the zero padding will occur after the sign.

If the '-' flag is not given, then the space padding will occur before the sign.

All flags defined for Byte, Short, Integer, and Long apply. The default behavior when no flags are given is the same as for Byte, Short, Integer, and Long.

The specification of width is the same as defined for Byte, Short, Integer, and Long.

The precision is not applicable. If precision is specified then an IllegalFormatPrecisionExceptionwill be thrown.

Float and Double

The following conversions may be applied to float, Float, double and Double.

'e' '\u0065'Requires the output to be formatted using computerized scientific notation. Thelocalization 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 thelocalization 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) orDouble.toString(double) respectively, then the value will be rounded using theround half up algorithm. Otherwise, zeros may be appended to reach the precision. For a canonical representation of the value, use Float.toString(float) orDouble.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 mdepends 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) orDouble.toString(double) respectively, then the value will be rounded using theround half up algorithm. Otherwise, zeros may be appended to reach the precision. For a canonical representation of the value,use Float.toString(float) orDouble.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 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.

If the '(' or ',' flags are given, then a FormatFlagsConversionMismatchExceptionwill 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').

All flags defined for Byte, Short, Integer, and Long apply.

If the '#' flag is given, then the decimal separator will always be present.

If no flags are given the default formatting is as follows:

  • The output is right-justified within the width
  • Negative numbers begin with a '-'
  • Positive numbers and positive zero do not include a sign or extra leading space
  • No grouping separators are included
  • The decimal separator will only appear if a digit follows it

The width is the minimum number of characters to be written to the output. This includes any signs, digits, grouping separators, decimal separators, exponential symbol, radix indicator, parentheses, and strings representing infinity and NaN as applicable. If the length of the converted value is less than the width then the output will be padded by spaces ('\u0020') until the total number of characters equals width. The padding is on the left by default. If the '-'flag is given then the padding will be on the right. If width is not specified then there is no minimum.

If the conversion is 'e', 'E' or 'f', then the precision is the number of digits after the decimal separator. If the precision is not specified, then it is assumed to be 6.

If the conversion is 'g' or 'G', then the precision is the total number of significant digits in the resulting magnitude after rounding. If the precision is not specified, then the default value is 6. If the precision is 0, then it is taken to be 1.

If the conversion is 'a' or 'A', then the precision is the number of hexadecimal digits after the decimal separator. If the precision is not provided, then all of the digits as returned byDouble.toHexString(double) will be output.

BigDecimal

The following conversions may be applied BigDecimal.

'e' '\u0065'Requires the output to be formatted using computerized scientific notation. Thelocalization 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 thelocalization 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) orDouble.toString(double) respectively, then the value will be rounded using theround 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 mdepends 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 which would appear after the decimal point in the string returned by Float.toString(float) orDouble.toString(double) respectively, then the value will be rounded using theround half up algorithm. Otherwise, zeros may be appended to reach the precision. For a canonical representation of the value, use BigDecimal.toString().

All flags defined for Byte, Short, Integer, and Long apply.

If the '#' flag is given, then the decimal separator will always be present.

The default behavior when no flags are given is the same as for Float and Double.

The specification of width and precision is the same as defined for Float and Double.

Date/Time

This conversion may be applied to long, Long, Calendar, and Date.

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

The following date and time conversion character suffixes are defined for the 't' and 'T'conversions. The types are similar to but not completely identical to those defined by GNU dateand POSIX strftime(3c). Additional conversion types are provided to access Java-specific functionality (e.g. 'L' for milliseconds within the second).

The following conversion characters are used for formatting times:

'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.
'Z' '\u005a'A string representing the abbreviation for the time zone.
'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:00UTC, 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.

The following conversion characters are used for formatting dates:

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

The following conversion characters are used for formatting common date/time compositions.

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

The '-' flag defined for General conversions applies. If the '#' flag is given, then aFormatFlagsConversionMismatchException will be thrown.

The width is the minimum number of characters to be written to the output. If the length of the converted value is less than the width then the output will be padded by spaces ('\u0020') until the total number of characters equals width. The padding is on the left by default. If the '-'flag is given then the padding will be on the right. If width is not specified then there is no minimum.

The precision is not applicable. If the precision is specified then anIllegalFormatPrecisionException will be thrown.

Percent

The conversion does not correspond to any argument.

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

The width is the minimum number of characters to be written to the output including the '%'. If the length of the converted value is less than 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 anIllegalFormatPrecisionException will be thrown.

Line Separator

The conversion does not correspond to any argument.

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

Flags, width, and precision are not applicable. If any are provided anIllegalFormatFlagsException, IllegalFormatWidthException, and IllegalFormatPrecisionException, respectively will be thrown.

Argument Index

Format specifiers can reference arguments in three ways:

  • Explicit indexing is used when the format specifier contains an argument index. The argument index is a decimal integer indicating the position of the argument in the argument list. The first argument is referenced by "1$", the second by "2$", etc. An argument may be referenced more than once.

    For example:

    formatter.format("%4$s %3$s %2$s %1$s %4$s %3$s %2$s %1$s", "a", "b", "c", "d") // -> "d c b a d c b a"
  • Relative indexing is used when the format specifier contains a '<' ('\u003c') flag which causes the argument for the previous format specifier to be re-used. If there is no previous argument, then a MissingFormatArgumentException is thrown.
    formatter.format("%s %s %<s %<s", "a", "b", "c", "d") // -> "a b b b" // "c" and "d" are ignored because they are not referenced
  • Ordinary indexing is used when the format specifier contains neither an argument index nor a'<' flag. Each format specifier which uses ordinary indexing is assigned a sequential implicit index into argument list which is independent of the indices used by explicit or relative indexing.
    formatter.format("%s %s %s %s", "a", "b", "c", "d") // -> "a b c d"

It is possible to have a format string which uses all forms of indexing, for example:

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

The maximum number of arguments is limited by the maximum dimension of a Java array as defined by the Java Virtual Machine Specification. If the argument index is does not correspond to an available argument, then a MissingFormatArgumentException is thrown.

If there are more arguments than format specifiers, the extra arguments are ignored.

Unless otherwise specified, passing a null argument to any method or constructor in this class will cause a NullPointerException to be thrown.

Since:
1.5

Nested Class Summary
static classFormatter.BigDecimalLayoutForm
           
 
Constructor Summary
Formatter()
          Constructs a new formatter.
Formatter(Appendable a)
          Constructs a new formatter with the specified destination.
Formatter(Appendable a, Locale l)
          Constructs a new formatter with the specified destination and locale.
Formatter(File file)
          Constructs a new formatter with the specified file.
Formatter(File file, String csn)
          Constructs a new formatter with the specified file and charset.
Formatter(File file, String csn, Locale l)
          Constructs a new formatter with the specified file, charset, and locale.
Formatter(Locale l)
          Constructs a new formatter with the specified locale.
Formatter(OutputStream os)
          Constructs a new formatter with the specified output stream.
Formatter(OutputStream os, String csn)
          Constructs a new formatter with the specified output stream and charset.
Formatter(OutputStream os, String csn, Locale l)
          Constructs a new formatter with the specified output stream, charset, and locale.
Formatter(PrintStream ps)
          Constructs a new formatter with the specified print stream.
Formatter(String fileName)
          Constructs a new formatter with the specified file name.
Formatter(String fileName, String csn)
          Constructs a new formatter with the specified file name and charset.
Formatter(String fileName, String csn, Locale l)
          Constructs a new formatter with the specified file name, charset, and locale.
 
Method Summary
 voidclose()
          Closes this formatter.
 voidflush()
          Flushes this formatter.
 Formatterformat(Locale l, String format, Object... args)
          Writes a formatted string to this object's destination using the specified locale, format string, and arguments.
 Formatterformat(String format, Object... args)
          Writes a formatted string to this object's destination using the specified format string and arguments.
 IOExceptionioException()
          Returns the IOException last thrown by this formatter's Appendable.
 Localelocale()
          Returns the locale set by the construction of this formatter.
 Appendableout()
          Returns the destination for the output.
 StringtoString()
          Returns the result of invoking toString() on the destination for the output.
 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, wait, wait, wait
 

Constructor Detail

Formatter

public Formatter()
Constructs a new formatter.

The destination of the formatted output is a StringBuilder which may be retrieved by invokingout() and whose current content may be converted into a string by invoking toString(). The locale used is the default locale for this instance of the Java virtual machine.


Formatter

public Formatter(Appendable a)
Constructs a new formatter with the specified destination.

The locale used is the default locale for this instance of the Java virtual machine.

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

Formatter

public Formatter(Locale l)
Constructs a new formatter with the specified locale.

The destination of the formatted output is a StringBuilder which may be retrieved by invokingout() and whose current content may be converted into a string by invoking toString().

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

Formatter

public Formatter(Appendable a, Locale l)
Constructs a new formatter with the specified destination and locale.
Parameters:
a - Destination for the formatted output. If a is null then a StringBuilder will be created.
l - The locale to apply during formatting. If l is null then no localization is applied.

Formatter

public Formatter(String fileName) throws FileNotFoundException
Constructs a new formatter with the specified file name.

The charset used is the default charset for this instance of the Java virtual machine.

The locale used is the default locale for this instance of the Java virtual machine.

Parameters:
fileName - 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

public Formatter(String fileName, String csn) throws FileNotFoundException,UnsupportedEncodingException
Constructs a new formatter with the specified file name and charset.

The locale used is the default locale for this instance of the Java virtual machine.

Parameters:
fileName - 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 - 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

public Formatter(String fileName, String csn, Locale l) throws FileNotFoundException,UnsupportedEncodingException
Constructs a new formatter with the specified file name, charset, and locale.
Parameters:
fileName - 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 - The name of a supported charset
l - 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

public Formatter(File file) throws FileNotFoundException
Constructs a new formatter with the specified file.

The charset used is the default charset for this instance of the Java virtual machine.

The locale used is the default locale for this instance of the Java virtual machine.

Parameters:
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

public Formatter(File file, String csn) throws FileNotFoundException,UnsupportedEncodingException
Constructs a new formatter with the specified file and charset.

The locale used is the default locale for this instance of the Java virtual machine.

Parameters:
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 - 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

public Formatter(File file, String csn, Locale l) throws FileNotFoundException,UnsupportedEncodingException
Constructs a new formatter with the specified file, charset, and locale.
Parameters:
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 - The name of a supported charset
l - 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

public Formatter(PrintStream ps)
Constructs a new formatter with the specified print stream.

The locale used is the default locale for this instance of the Java virtual machine.

Characters are written to the given PrintStream object and are therefore encoded using that object's charset.

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

Formatter

public Formatter(OutputStream os)
Constructs a new formatter with the specified output stream.

The charset used is the default charset for this instance of the Java virtual machine.

The locale used is the default locale for this instance of the Java virtual machine.

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

Formatter

public Formatter(OutputStream os, String csn) throws UnsupportedEncodingException
Constructs a new formatter with the specified output stream and charset.

The locale used is the default locale for this instance of the Java virtual machine.

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

Formatter

public Formatter(OutputStream os, String csn, Locale l) throws UnsupportedEncodingException
Constructs a new formatter with the specified output stream, charset, and locale.
Parameters:
os - The output stream to use as the destination of this formatter. The output will be buffered.
csn - The name of a supported charset
l - The locale to apply during formatting. If l is null then no localization is applied.
Throws:
UnsupportedEncodingException - If the named charset is not supported
Method Detail

locale

public Locale locale()
Returns the locale set by the construction of this formatter.

The format method for this object which has a locale argument does not change this value.

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

out

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

toString

public String toString()
Returns the result of invoking toString() on the destination for the output. For example, the following code formats text into a StringBuilder then retrieves the resultant string:
Formatter f = new Formatter(); f.format("Last reboot at %tc", lastRebootDate); String s = f.toString(); // -> s == "Last reboot at Sat Jan 01 00:00:00 PST 2000"

An invocation of this method behaves in exactly the same way as the invocation

out().toString()

Depending on the specification of toString for the Appendable, the returned string may or may not contain the characters written to the destination. For instance, buffers typically return their contents in toString(), but streams cannot since the data is discarded.

Overrides:
toString in class Object
Returns:
The result of invoking toString() on the destination for the output
Throws:
FormatterClosedException - If this formatter has been closed by invoking its close()method

flush

public void flush()
Flushes this formatter. If the destination implements the Flushable interface, its flushmethod will be invoked.

Flushing a formatter writes any buffered output in the destination to the underlying stream.

Specified by:
flush in interface Flushable
Throws:
FormatterClosedException - If this formatter has been closed by invoking its close()method

close

public void close()
Closes this formatter. If the destination implements the Closeable interface, its closemethod will be invoked.

Closing a formatter allows it to release resources it may be holding (such as open files). If the formatter is already closed, then invoking this method has no effect.

Attempting to invoke any methods except ioException() in this formatter after it has been closed will result in a FormatterClosedException.

Specified by:
close in interface Closeable

ioException

public IOException ioException()
Returns the IOException last thrown by this formatter's Appendable.

If the destination's append() method never throws IOException, then this method will always return null.

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

format

public Formatter format(String format, Object... args)
Writes a formatted string to this object's destination using the specified format string and arguments. The locale used is the one defined during the construction of this formatter.
Parameters:
format - A format string as described in Format string syntax.
args - Arguments referenced by the format specifiers in the format string. If there are more arguments than format specifiers, the extra arguments are ignored. The maximum number of arguments is limited by the maximum dimension of a Java array as defined by the Java Virtual Machine Specification.
Returns:
This formatter
Throws:
IllegalFormatException - If a format string contains an illegal syntax, a format specifier that is incompatible with the given arguments, insufficient arguments given the format string, or other illegal conditions. For specification of all possible formatting errors, see the Details section of the formatter class specification.
FormatterClosedException - If this formatter has been closed by invoking its close()method

format

public Formatter format(Locale l, String format, Object... args)
Writes a formatted string to this object's destination using the specified locale, format string, and arguments.
Parameters:
l - 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 - A format string as described in Format string syntax
args - Arguments referenced by the format specifiers in the format string. If there are more arguments than format specifiers, the extra arguments are ignored. The maximum number of arguments is limited by the maximum dimension of a Java array as defined by the Java Virtual Machine Specification
Returns:
This formatter
Throws:
IllegalFormatException - If a format string contains an illegal syntax, a format specifier that is incompatible with the given arguments, insufficient arguments given the format string, or other illegal conditions. For specification of all possible formatting errors, see the Details section of the formatter class specification.
FormatterClosedException - If this formatter has been closed by invoking its close()method
基于SpringBoot+Vue的个性化英语学习系统毕业设计全栈实现 个性化推荐系统通过分析用户行为数据,为不同学习者提供定制化的内容与路径,其核心原理在于协同过滤、内容过滤等算法对用户-项目交互矩阵的挖掘。这项技术在教育、电商、内容平台等领域具有重要价值,能有效提升用户参与度与学习效率。在在线教育场景中,结合Java SpringBoot后端与Vue前端技术栈,可以构建高效、可扩展的个性化学习应用。本文以英语学习辅助系统为例,详细拆解了从需求分析、数据库设计、核心算法(如用户协同过滤)实现到前后端分离开发的全流程,并融入了热词hanlp分词在springboot进行内容分析 阅读详情

相关推荐

Linux内核本质:不是操作系统,也不是CPU芯片

内核是运行在Ring 0特权级的系统软件核心,负责CPU调度、内存隔离、设备I/O仲裁和系统调用接口四大职能。它并非操作系统本身(如Ubuntu),也非物理硬件(如CPU芯片),而是一段约25MB的纯软件逻辑镜像(vmlinux)。其‘不可见性’源于用户/内核双地址空间设计——通过x86-64的48位虚拟地址划分与硬件级特权切换(syscall指令),实现进程在用户态与内核态间的无缝上下文迁移。这种架构支撑了高性能系统调用(300–500周期)、DMA零拷贝I/O及安全内存保护(SMAP/SMEP),广泛应

weixin_30615767的博客 467

Java源码阅读神器之Translation翻译插件

Translation插件主要是用来翻译工作的,我们学习源码时,遇到注释有不认识的单词时需粘贴到某某翻译查看,使用此插件在当前界面通过快捷键或鼠标右击的方式即可完成翻译工作中。

qq_38939215的博客 7304

Linux内核四大支柱:调度、内存、I/O与安全机制解析

内核(Kernel)是操作系统与硬件之间的核心枢纽,负责资源抽象、权限管控与系统协调。其本质是一套运行在CPU最高特权级的精密契约体系,通过系统调用提供受控访问接口。核心原理围绕四大子系统展开:CPU调度器实现公平时间片分配与上下文切换;内存管理构建虚拟地址空间,支撑隔离、swap与OOM控制;I/O子系统统一设备驱动模型与页缓存机制,平衡性能与一致性;安全框架依托ring0/ring3隔离、SELinux等强制访问控制保障最小权限。这些机制共同支撑云计算、AI训练(如PyTorch CUDA错误)、嵌入式

weixin_34357436的博客 409

java复习 事务

数据库怎么存放数据 : 先把数据放到表里 再把表放到数据库里 一个数据库可以有多个表 表名字不能相同 表有一些特征,这些特性定义了数据库在表中如何存储 表由列组成,我也成为字段所有表都是由一列或者多列组成的 表中的数据是按行存储的 什么是事务(Translation) 数据库的事务是指一组sql语句组成的数据库逻辑处理单元,在这组的sql操作中,要么全部执行成功,要么全部执行失败 事务是一个不可分割的数据库操作序列,也就是数据库控制并发控制的基本单位; 组成: 一个数据库事务通常包含对数据库进行读和写的一个

weixin_42384355的博客 144

Java Idea TranslationPlugin翻译插件使用解析

主要介绍了Java Idea TranslationPlugin翻译插件使用解析,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下

R语言绘图中文显示全攻略:从乱码到完美适配

本文详细解析了R语言绘图中的中文显示问题,从乱码根源到完美适配方案。通过showtext、sysfonts和extrafont等工具包的应用,提供跨平台的中文显示解决方案,涵盖ggplot2图表、PDF/PNG输出及Shiny应用等场景,助力用户高效实现R绘图中文完美呈现。

hp777的博客 260

Java学习笔记之Formatter的用法详解(输出格式化)

java.util.Formatter (摘自sun主页) Implements: Closeable, Flushable Inner classes: Formatter.BigDecimalLayoutForm printf 风格的格式字符串的解释程序。此类提供了对布局对齐和排列的支持,以及对数值、字符串和日期/时间数据的常规格式和特定于语言环境的输出的支持。支持诸如...

1023

c语言压力变送器程序设计,基于单片机的压力变送器设计

基于单片机的压力变送器设计(任务书,开题报告,外文翻译,论文15000字,代码)摘要随着工业化水平的不断提高,新型智能仪表在工业生产过程中运用也越来越广泛,同时对输出数据的准确检测和处理也变得至关重要。生产过程的运行和设备安全是极其重要的,那么如何实现对其精确的检测呢?众所周知,在工业生产过程中有一个很重要参数——压力,显然这个参数是一个必不可少的条件。故而,研究智能压力变松器系统对工业生产有着不...

weixin_33681561的博客 1963

如何在 Java 中翻译语言

虽然这些个人和商业联系教会了我们很多关于我们各种文化的知识,但我们仍然会遇到语言障碍。这些障碍会给用户和企业带来相当大的不便和挫败感,这就是为什么语言翻译技术的发展如此有价值的原因。如果您需要在英语和法语、德语或俄语之间自动进行语言翻译,我们有一些 API 可以帮助您。自从互联网在二十世纪末成为人们关注的焦点以来,它一直在为促进大规模的全球化尽自己的一份力量。在这里,您将输入您的翻译请求,实例化 API,并为您的特定请求调用函数。每个 API 都将从相同的几个步骤开始,但在创建 API 实例时会发生变化。

免费 638

Marin说PCB之LPDDR5的布线注意事项--03

这个规则中是把每个字节中的WCK to RDQS 以及DM / DQ to WCK等长规则都加到了DM / DQ这个等长规则中去了,因为芯片手册上的设计要求中的DM / DQ这个group的等长误差是+-50MIL, WCK to RDQS的等长group的规则是62.5MIL,DM / DQ to WCK等长group的规则是相对松一些是150MIL。其实上面的等长规则还是建少了一些的,例如手册上要求的每个channel的WCK0:1,WCK2:3等长误差在+-488MIL,这个规则建议还是补上去吧。

weixin_45223454的博客 1230

STC51单片机串口多字节数据接收的优化策略

本文深入探讨了STC51单片机串口多字节数据接收的优化策略。针对数据丢包、粘包等常见痛点,核心思路是采用“缓冲队列+定时器超时”模式,将实时处理转变为“先收纳,后处理”。文章详细讲解了硬件初始化、中断服务程序优化(快速入队与激活超时裁判)以及主循环的非阻塞设计,并进阶介绍了环形缓冲区实现与错误处理,旨在构建稳定可靠的串口通信系统。

weixin_29264201的博客 374

Translation_java_StringBuffer

_ 代表要翻译 此颜色代表上文已翻译 (%) %解释下划线 此颜色代表翻译词组 java.lang Class StringBuffer java.lang.Object java.lang.StringBuffer All Implemented Inter...

管子(zero)的杂乱空间 148

笔试题-2023-乐鑫-数字IC设计【纯净题目版】

笔试题-2023-乐鑫-数字IC设计【纯净题目版】

w0shishabi的博客 1779

[idea插件推荐] 键盘流最爱,开发快到飞起

导言 磨刀不误砍柴工,好的开发环境对开发效率的影响是毋庸置疑的,以下推荐一些我常用的idea插件 必装插件 Lombok 几乎是每个项目都有用的lombok, 必安。 Maven Helper 便于直观查看maven依赖冲突的问题 Alibaba Java Coding Guidelines 各种规范提示,写出更优秀、优美的代码 Free MyBatis plugin free-idea-mybatis是一款增强idea对mybatis支持的插件,主要功能如下: 生成mapper xml文件 快速从代码

陈浩的博客 2201

Vue2 - 最新详细实现网站内部打开预览 office 全套附件,在页面弹窗内解析预览 word文档、excel电子表格、ppt演示文稿(docx|xlsx|pptx|pdf|txt等文件)详细代码

vue2,nuxt2,office,文档,文件,查看预览,弹框预览,下载预览,如何预览pdf文档,打开查看,office全套文档,实现在线预览文件,小程序内预览word文件,手机h5移动端网页,nuxt文档在线预览,预览office最好用的插件,下载查看,Office在线预览,vue-office,vue如何使用vue-office教程示例,word文档,ppt,exce表格,预览电子文件,文档无法解析,打不开,报错,失效,保存下载,vue前端预览并下载doc、xls、pdf、txt及图片,vue2中预览p

🏆 前端领域优质创作者 1万+

使用Simulink进行无刷电机霍尔传感器信号处理电路的仿真

位置检测:霍尔传感器可以检测转子的位置,这对于实现无刷电机的电子换向至关重要。提高效率:通过准确的位置信息,可以优化电机的工作状态,提高效率和性能。通过上述步骤,我们简要介绍了如何基于Simulink实现无刷电机霍尔传感器信号处理电路的仿真。

MHD0815的博客 432

深入拆解translation项目结构:如何搭建自己的Java技术翻译知识库

translation项目(CNCounter)是一个持续多年的开源 Java 技术翻译知识库:全仓库包含 **661 篇 Markdown 译文**和 **610 张配图**,覆盖 JVM、GC、MySQL、Redis、Spring 等热门主题。本文将深入拆解它的目录组织方式,并给出一份可直接照做的清单,教你搭建属于自己的技术文章翻译知识库。 [![translation项目知识库中的JVM结

gitblog_00360的博客 1061

【实战项目开发技术分享】如何设置机器人禁行区/虚拟墙

在现代机器人技术的日益发展中,路径规划是使机器人在复杂环境中安全、高效移动的关键部分。其中一个重要的问题是如何划定机器人的禁行区,以确保机器人不会进入危险区域或无法到达的地方。在本文中,我们将探讨一些关键策略,帮助机器人算法工程师更好地划定禁行区。代价地图可以通过多层叠加来实现,一般包括以下几个层级:静态地图层(Static Map Layer):由SLAM(Simultaneous Localization and Mapping)构建的静态地图。该层包含了环境中固定不变的地物信息,如墙壁、家具等。

xiewf的博客 1万+

提升效率神器:Sql-Translation——JSON转SQL的利器

提升效率神器:Sql-Translation——JSON转SQL的利器 项目介绍 在现代数据处理中,JSON和SQL是两种最常用的数据格式。然而,将JSON数据转换为SQL语句的过程往往繁琐且耗时。为了解决这一痛点,Sql-Translation(简称ST)应运而生。ST是一个专门用于将JSON数据转换为SQL语句的工具,旨在通过自动化处理,帮助开发者节省时间,提高工作效率。 项目技术分析 前端技...

gitblog_00906的博客 1617

霍尼韦尔SoftMaster使用说明

霍尼韦尔SoftMaster使用说明

老版QQ原生表情gif动态

这是老版的QQ表情,不过全是动态的的,Windows照片查看器是不会动的,可以右击用浏览器打开查看,再说一遍是老版的,只是分享给宁愿用老版也要动态的人。

Intellij IDEA plugin 开发最常用插件

lombok plugin p3c 阿里巴巴代码检查工具 GsonFormat json和java对象转换工具 GenerateAllSetter new 对象 赋值时 自动生成对象的所有set FindBugs-IDEA 自动扫描项目中的bug VisualVM Launcher 启动java项目时 自动启动jvisualvm 监控内存占用 Mybatisx mybatis自动生成工具 .........

zhaoyang10的专栏 6284

VC中sqlite的使用

在VC中对sqlite的使用,实现数据库大批数据的快速插入,读取数据库中的数据在ListCtrl中显示

从分支栈到批量PR:git-spice一条stack submit命令提交整栈变更请求实战教程

git-spice 是一款免费开源的分支栈(Stacked Branches)管理工具,它的核心杀手锏就是 `gs stack submit` 这一条命令:可以把当前分支栈中所有分支批量推送,并为每个分支自动创建或更新拉取请求(GitHub/Gitea/Forgejo 上叫 Pull Request,GitLab 上叫 Merge Request),支持 GitHub、GitLab、Bitbuck

gitblog_00290的博客 777

Data-Structures-and-Algorithm-Analysis-in-Java.pdf

作者: Weiss, Mark A. 出版社: Addison Wesley Data Structures and Algorithm Analysis in Java is an “advanced algorithms” book that fits between traditional CS2 and Algorithms Analysis courses. In the old ACM Curriculum Guidelines, this course was known as CS7. This text is for readers who want to learn good programming and algorithm analysis skills simultaneously so that they can develop such programs with the maximum amo...

开发小记 - 常用设置

开发中一些常用的设置

Sun 900

为什么选择RTranslator:保护隐私的终极离线翻译解决方案

还在为语言障碍而烦恼吗?RTranslator是一款革命性的Android实时翻译应用,它最大的优势在于**完全离线运行**,保护您的隐私安全,让您无需网络即可享受高质量的多语言翻译体验。这款开源免费的应用基于顶尖AI技术,将Meta的NLLB翻译模型和OpenAI的Whisper语音识别模型完美集成到移动设备中,为您提供真正的隐私保护翻译解决方案。 ## 项目核心价值定位:重新定义移动翻译体验

gitblog_01124的博客 752

IDEA插件实战指南:从代码质量到开发效率的全面优化

在软件开发领域,集成开发环境(IDE)是程序员的核心生产力工具,而插件生态则是其能力延伸的关键。插件通过扩展IDE的固有功能,遵循自动化与效率优先的原则,将重复性劳动转化为一键操作,其技术价值在于显著降低人为错误、统一团队规范并提升代码可维护性。从静态代码分析、实时质量检测到可视化依赖管理和自动化代码生成,插件在代码质量守护、开发流程加速及团队协作等核心应用场景中发挥着重要作用。本文聚焦于IntelliJ IDEA这一主流Java IDE,深入探讨如SonarLint、Lombok、MyBatisX等经过实

weixin_30372371的博客 381

实战指南:如何快速掌握AIOS智能代理操作系统

在AI代理开发领域,开发者常常面临系统资源管理混乱、多模型调度困难、工具调用不一致等痛点。AIOS(AI Agent Operating System)作为一个创新的AI代理操作系统,通过将大语言模型深度集成到操作系统内核,为AI代理开发者提供了一站式解决方案。本文将带你从零开始,全面掌握AIOS的核心功能与实战应用。 ## 从痛点出发:AI代理开发的三大挑战 在传统AI代理开发中,开发者需要

gitblog_00886的博客 355
下一篇: oracle 基础及权限
without0815
博客等级 码龄15年 107粉丝 79原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

当前余额3.43元 前往充值 >
需支付:10.00元
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付元
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值