JDK5 new features: Formatted output

Source: Internet
Author: User
Tags character set iso 8601 locale lowercase posix reserved string format java format

DK5.0 allow like C language as direct use printf () method to format the output, and a number of parameters are provided to format the input, and the invocation is simple:

System.out.format ("Pi is approximately%f", Math.PI);

System.out.printf ("Pi is approximately%f", Math.PI);

printf () and format () method has the same functionality . System.out is an example of java.io.PrintStream . PrintStream, Java.io.PrintWriter, and java.lang.String Each class has four new formatting methods :

Format (String format, Object ... args);

printf (String format, Object ... args);

Format (Locale Locale, String format, Object ... args);

printf (Locale Locale, String format, Object ... args);

at the same time, the previous Formatter class also provides a more sophisticated way to format, for example:

Formatter.format ("Pi is approximately%1$f," +

"and E is about%2$f", Math.PI, MATH.E);

The formatting elements are composed as follows:

%[argument_index$][flags][width][.precision]conversion

which

Argument_index is a positive integer that illustrates the position of the parameter, 1 to take the first argument

width represents the minimum number of letters in the output

Precision Number of decimal places to represent numbers

Conversion represents the type of the parameter being formatted:

F Float,

T time

D Decimal

o Octal

x hexadecimal

S General

c a Unicode character

Here's an example:

Package format;

Import Java.util.Formatter;

public class Usingformatter {

public static void Main (string[] args) {

if (args.length!= 1) {

System.err.println ("Usage:" +

"Java Format/usingformatter");

System.exit (0);

}

String format = args[0];

StringBuilder StringBuilder = new StringBuilder ();

Formatter Formatter = new Formatter (StringBuilder);

Formatter.format ("Pi is approximately" + format +

", and E is about" + format, Math.PI, MATH.E);

System.out.println (StringBuilder);

}

}

// Console Call

Java format/usingformatter%f

// Output

Pi is approximately 3.141593, and E is about 2.718282

// Console Call

Java format/usingformatter% 2f

// Output

Pi is approximately 3.14, and E is about 2.72

// Console Call

Java format/usingformatter% 6.2f

// Output ( with space to fill the length )

Pi is approximately 3.14, and E is about 2.72

// Console Call

Java format/usingformatter%1$ 2f

// Output

Pi is approximately 3.14, and E is about 3.14

// Change Regional Settings

Package format;

Import Java.util.Formatter;

Import Java.util.Locale;

public class Usingformatter {

public static void Main (string[] args) {

if (args.length!= 1) {

System.err.println ("Usage:" +

"Java format/usingformatter <format string>");

System.exit (0);

}

String format = args[0];

StringBuilder StringBuilder = new StringBuilder ();

Formatter Formatter = new Formatter (StringBuilder,

Locale.france);

Formatter.format ("Pi is approximately" + format +

", and E is about" + format, Math.PI, MATH.E);

System.out.println (StringBuilder);

}

}

// Console Call

Java format/usingformatter% 2f

// Output

Pi is approximately 3,14, and e are about 2,72

// Adopt format,printf Alternative formulation of

Package format;

public class Usingsystemout {

public static void Main (string[] args) {

if (args.length!= 1) {

System.err.println ("Usage:" +

"Java format/usingsystemout <format string>");

System.exit (0);

}

String format = args[0];

System.out.format ("Pi is approximately" + format +

", and E is approximately" + format, Math.PI, MATH.E);

}

}

// Console Call

Java format/usingsystemout% . 2f %n

// Output

Pi is approximately 3.14

, and E is about 2.72

The format of time with letters T to represent, usually in T followed by a special character to show a part of the time:

Tr hour and minute,

TA the day of the week

TB the name of the month

Te the number of the day of the month

TY the Year

eg.

Package format;

Import Java.util.Calendar;

public class Formattingdates {

public static void Main (string[] args) {

System.out.printf ("Right now it's%tr on" +

"%<ta,%<TB%<te,%<ty.%n",

Calendar.getinstance ());

}

}

// Description: " < "indicates that the parameter used is the previous formatted parameter

// Output

Right now it's 01:55:19 PM on Wednesday, September 22, 2004.




syntax for format Strings

format strings are required for each method that produces the formatted output and a list of parameters. A format string is a stringthat can 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 format the first parameter of the method. It contains three format specifiers "%1$tm","%1$te" , and "%1$ty". They indicate how parameters should be handled and where they are inserted in the text. The remainder of the format string is a fixed text that includes "Dukes Birthday:" and any other space or punctuation. The argument list consists of all the parameters passed to the method that is located after the format string. In the example above, the argument list has a size of 1and consists of Calendar ofnew objects .

The syntax for format specifiers for general types, character types, and numeric types is as follows:

%[argument_index$][flags][width][.precision]conversion

Optional Argument_index is a decimal integer that indicates the position of the parameter in the parameter list. The first parameter is referenced by "1$" , the second parameter is referenced by "2$" , and so on.

Optional Flags is the character set that modifies the output format. The collection of valid flags depends on the type of conversion.

Optional width is a nonnegative decimal integer indicating the minimum number of characters to write to the output.

Optional Precision is a nonnegative decimal integer that is typically used to limit the number of characters. Specific behavior depends on the type of conversion.

of the required Conversion is a character that indicates how the parameter should be formatted. The set of valid conversions for a given parameter depends on the data type of the parameter.

The syntax for formatting specifiers that represent date and time types is as follows:

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

Optional Argument_index , Flags and the definition of width ibid.

of the required Conversion is a sequence consisting of two characters. The first character is ' t ' or ' t'. The second character indicates the format used. These characters are similar but not exactly equivalent to those defined by GNU date and POSIX strftime ( 3c ) .

The syntax for the format specifier that does not correspond to the parameter is as follows:

%[flags][width]conversion

Optional Flags and the definition of width ibid.

of the required Conversion is a character that indicates the content to be inserted in the output.

Convert

conversions can be grouped into the following categories:

General - can be applied to any parameter type

character - can be applied to represent Unicode basic type of character: Char , Character , byte , Byte , Short and short. When character.isvalidcodepoint (int) returns true , this transformation can be applied to int and Integer Types

Numerical

integers - can be applied to Java the integer type: byte , Byte , Short , Short , int , Integer , Long , Long and BigInteger

floating point - can be used to Java the floating-point type: float , Float , Double , Double and BigDecimal

Date / Time - can be applied to Java , the type that can encode a date or time: Long , Long , Calendar and Date.

percent - produce literal value ' % ' (' u0025 ')

Row Separator - generate platform-specific row delimiters

The following table summarizes the supported transformations. By uppercase characters such as ' B',' ' H ', ' 'S', ' 'C ' , ' ' X ' , ' E ' , ' G ' , ' A ' and ' T ') represent a conversion equivalent to that of a corresponding lowercase character, except that the result is converted to uppercase according to popular Locale rules. The latter is equivalent to the following call to string.touppercase ()

out.touppercase ()

Convert

parameter category

Description

"B", "B"

general

if parameter arg is null , the result is "false" . If the arg is a boolean value or boolean , the result is a string returned by string.valueof () . Otherwise the result is "true" .

"H", "H"

general

if parameter arg to null , the result is . Otherwise, the result is the result of calling integer.tohexstring (Arg.hashcode ()) .

' s ', ' s '

General

if the parameter Arg is null, the result is "null." If arg implements formattable, the Arg.formatto is invoked . Otherwise, the result is the result of the call to arg.tostring () .

' C ', ' C '

character

The result is a Unicode character

' d '

integers

The result is formatted as a decimal integer

' O '

integers

The result is formatted as an octal integer

' x ', ' x '

integers

The result is formatted as a hexadecimal integer

' E ', ' e '

floating point

The result is formatted as a decimal number in the computer science notation notation

' F '

floating point

The result is formatted as a decimal number

' G ', ' G '

floating point

The results are formatted using computer science notation or decimal format, depending on the precision and value after the rounding operation.

' A ', ' a '

floating point

The result is formatted as a hexadecimal floating-point number with a valid digit and exponent

' t ', ' t '

Date / Time

prefix for date and time conversion characters. See also date / time conversion .

''%''

percent

The result is the literal value ' % ' (' u0025 ')

' N '

Row Separator

The result is platform-specific row delimiters

any character that is not explicitly defined as a conversion is an illegal character and is reserved for future extended use.

Date / Time Conversion

the following date and time the suffix characters are converted to ' t ' and the ' T ' transformation is defined. These types are similar but not exactly equivalent to those defined by the GNU date and POSIX strftime ( 3c ) . Other transformation types are provided to access Java -specific features (such as using ' L ' as milliseconds in seconds).

The following conversion characters are used to format the time:

' H '

- Hours of the hour, are formatted as necessary with a leading zero of the two digits, that is 00-23 .

' I '

of Hours of the hour, are formatted as necessary with a leading zero of the two digits, that is 01-12 .

"' K '"

- Hours of the hour, that 0-23 .

' L '

of Hours of the hour, that 1-12 .

' M '

The minutes in the hour are formatted as a two-digit number with a leading zero if necessary, i.e. 00-59 .

' S '

The seconds in minutes are formatted as if necessary with a leading zero of two digits, i.e. 00-60 ( "a" is a special value that is required to support leap seconds.

' L '

The millisecond in seconds is formatted as a three-digit number with a leading zero if necessary, i.e. 000-999 .

' N '

The nanosecond in seconds is formatted as a nine-digit number with a leading zero if necessary, i.e. 000000000-999999999 .

' P '

Locale-specific morning or afternoon tokens are represented in lowercase, such as "AM" or "PM" . Use the conversion prefix ' T ' to forcibly convert this output to uppercase.

' Z '

relative to GMT the RFC 822 format of the digital time zone offset, for example, -0800.

' Z '

A string representing the abbreviated form of the time zone. the Formatter locale replaces the parameter's locale (if any).

' s '

Self-coordinating world time (UTC) 1970 years 1 Month 1 The number of seconds 00:00:00 to the present, that is, long.min_value/1000 and long.max_ The difference between the value/1000.

' Q '

Self-coordinating world time (UTC) 1970 years 1 Month 1 The number of milliseconds 00:00:00 to the present, i.e. long.min_value and long.max_value the difference between the values.

The following conversion characters are used to format dates:

' B '

Locale-specific Full Month , such as "January" and "February".

' B '

Locale-specific month abbreviation , such as " a few." and "Feb".

' H '

Same as ' b ' .

' A '

Locale-specific Day of the week full name, such as "Sunday" and "Monday"

' A '

Locale-specific Day of the week abbreviation, for example "Sun" and "Mon"

"' C '"

divided by - the four-digit year is formatted as a two-digit number with a leading zero if necessary, i.e. 00-99

' Y '

The year is formatted as a four-digit number (at least) with a leading zero if necessary, for example, 0092 equal to the Gregorian calendar. CE .

' Y '

The last two digits of the year are formatted as a two-digit number with a leading zero if necessary, i.e. 00-99 .

' J '

The number of days in a year is formatted as a three-digit number with a leading zero if necessary, for example, for the Gregorian calendar is 001-366 .

' m '

The month is formatted as a two-digit number with a leading zero if necessary, i.e. 01-13 .

' d '

The number of days in one months is formatted as necessary with a leading 2-digit number, which is 01-31

' E '

The number of days in one months is formatted as two digits, i.e. 1-31 .

The following conversion characters are used to format common dates / time combination.

' R '

- hours of time, are formatted as "%th:%tm"

' T '

- hours of time, are formatted as "%th:%tm:%ts" .

' R '

of hours of time, are formatted as "%ti:%tm:%ts%tp" . The location of the morning or afternoon marker ('%tp ') may be related to the locale.

' D '

date, which is formatted as "%tm/%td/%ty" .

' F '

ISO 8601 the full date of the format, which is formatted as "%TY-%TM-%TD" .

"' C '"

date and time, are formatted as "%ta%tb%td%tt%tz%ty" , such as "Sun June 16:17:00 EDT 1969" .

any character that is not explicitly defined as a conversion is an illegal character and is reserved for future extended use.

Sign

The following table summarizes the supported flags. y indicates that the flag is supported by the indicated parameter type.

The result will be left-aligned.

results should use alternate forms that depend on the conversion type

results always include a symbol

y

results will be populated with zero

results will include locale-specific

td>

flag

< span> General

character

integer

floating-point

date / time

description

y

y

y

< Span lang= "en-us" >y

y

"#"

y1

-

y3

< Span lang= "en-us" >y

-

"+"

-

-

y4

< Span lang= "en-us" >y

-

'    '

"0"

< Span lang= "en-us" >-

-

<" Span lang= "en-us" >y

-

-

-

y2

< Span lang= "en-us" >y5

-

''(''

-

-

Y4

Y5

-

The result will be a negative number enclosed in parentheses.

1 depends on formattable the definition.

2 applies only to ' d ' conversion.

3 applies only to ' o ' , ' x ' and ' X ' conversion.

4 Apply ' d',' o ',' x ' to BigInteger and the ' X ' conversion, or the byte and byte, Short and short,int and Integer,Long and Long apply ' d ' conversions respectively .

5 applies only to ' e ' , ' E ' , ' F ' , ' g ' and ' G ' conversion.

any characters that are not explicitly defined as flags are illegal characters and are preserved for extended use.

width

The width is the minimum number of characters that will be written to the output. For row delimiter conversions, width is not applicable, and if width is provided, an exception is thrown.

Precision

for general parameter types, the precision is the maximum number of characters that will be written to the output.

for 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 all the digits of the value that is rounded after the calculation. If the conversion is ' a ' or ' a', you do not have to specify the precision.

for characters, integers, and dates / Time parameter type conversions, as well as percentages and row delimiter conversions, the precision is not applicable, and if the precision is supplied, an exception is thrown.

parameter Index

A parameter index is a decimal integer that indicates the position of the parameter in the parameter list. The first parameter is referenced by "1$" , the second parameter is referenced by "2$" , and so on.

Another way to refer to a parameter based on position is to use the ' < ' (' u 003c ') flag, which will reuse the parameters of the previous format specifier. For example, the following two statements produce the same characters:

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);







</

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.