In JavaSe5, the formatted output of the printf () style is introduced in the C language. This not only makes it easier to control the output code, but also gives Java developers greater control over the output format and arrangement. Today, we begin to learn about formatted output in Java.
Directory Navigation
- System.out.format ()
- Formatter class
- Format specifier
- Formatter conversion
- Simple 16-Binary conversion tool
- Friendship Link
System.out.format ()
As the content is relatively simple, we use examples to illustrate. The project structure is as follows:
The format method introduced by Java Se5 can be used with PrintStream or PrintWriter objects, which also include System.out objects.
PackageCom.tomhu.format; Public classFormatTest1 { Public Static voidMain (string[] args) {intx = 5; Doubley = 3.141592; //General WaySystem.out.println ("x =" + x + ", y =" +y); //printf () modeSystem.out.printf ("x =%d, y =%f\n"), x, y); //format () modeSystem.out.format ("x =%d, y =%f\n"), x, y); }}
The results of the output are as follows:
x = 5, y = 3.141592= 5, y = 3.141592= 5, y = 3.141592
As you can see, format and printf are equivalent, they only need a simple format string, plus a string of parameters, each parameter corresponds to a format modifier.
Public printstream printf (String format, Object ... args) { return format (format, args);}
In the specific code of format, it is actually called the format method of formatter: Formatter.format (Locale.getdefault (), format, args);
Publicprintstream Format (String format, Object ... args) {Try { synchronized( This) {ensureopen (); if(Formatter = =NULL) || (Formatter.locale ()! =Locale.getdefault ())) Formatter=NewFormatter ((appendable) This); Formatter.format (Locale.getdefault (), format, args); } } Catch(Interruptedioexception x) {Thread.CurrentThread (). interrupt (); } Catch(IOException x) {Trouble=true; } return This;}
Formatter class
In Java, all new formatting functions are handled by the formatter class, as is the printf and format described above. Formatter can be thought of as a translator that translates your formatted strings and data into desired results. When you create a formatter object, you need to pass some information to its constructor, telling it where the final result will be output
package Com.tomhu.format; import Java.util.Formatter; public class FormatTest2 { static void main (string[] args) {String Name = "Huhx" ; int age = 22; Formatter Formatter = new Formatter ( System.out); Formatter.format ( "My name is%s, and my age is%d"
It outputs the following results:
Format specifier
When inserting data, if you want to control the spacing and alignment, you need a sophisticated format modifier, the following is its abstract syntax:
%[argument_index$][flags][width][.precision]conversionthe 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. The optional flags are a set of characters that modify the output format. The set of valid flags depends on the conversion. The optional width is a non-Negative decimal integer indicating the minimum number of characters to is 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 being formatted. The set of valid conversions forA given argument depends on the argument ' s data type.
The most common application is to control the minimum size of a field, which can be achieved by specifying width . The formatter object ensures that a field reaches at least a certain length by adding spaces when necessary. By default, the data is right-aligned , and the "-" flag allows you to change the orientation of the alignment.
Relative to width is the precision (precision), which is used to indicate the maximum size. Width can apply various types of data transformations, and they behave the same way. Precision is not the same, not all types of data can use precision, and, when applied to different types of data transformations, precision has a different meaning.
- When precision is applied to a string, it represents the maximum number of output characters when a string is printed
- When precision is applied to floating-point numbers, it represents the number of digits to be displayed for the decimal point. The default is 6 decimal places, which are rounded if the number of decimal places is too large and too little is 0 at the tail.
- because integers do not have fractional parts, precision cannot be applied to integers. If you apply precision to integers, it triggers an abnormal
PackageCom.tomhu.format;ImportJava.util.Formatter; Public classFormatTest3 {StaticFormatter Formatter =NewFormatter (System.out); Public Static voidPrintTitle () {Formatter.format ("%-15s%-5s%-10s\n", "Huhx", "Linux", "Liuli"); Formatter.format ("%-15s%-5s%-10s\n", "Zhangkun", "Yanzi", "Zhangcong"); Formatter.format ("%-15s%-5s%-10s\n", "Zhangkun", "Yanzhou", "Zhangcong"); } Public Static voidprint () {Formatter.format ("%-15s%5d%10.2f\n", "My name is Huhx", 5, 4.2); Formatter.format ("%-15.4s%5d%10.2f\n", "My name is Huhx", 5, 4.1); } Public Static voidMain (string[] args) {printtitle (); System.out.println ("----------------------------"); Print (); Formatter.close (); }}
It outputs the following results:
huhx linux liuli zhangkun yanzi zhangcong zhangkun ----------------------------My Name is HUHX 5 4.20My n 5 4.10
Formatter conversion
The following table contains the most commonly used type conversions:
Type conversion character
| D |
Integer type (10 binary) |
E |
Floating point number (scientific counting) |
| C |
Unicode characters |
X |
Integer (16 binary) |
| B |
Boolean value |
H |
hash code (16 binary) |
| S |
String |
% |
Character "%" |
| F |
Floating point (10 binary) |
|
|
String.Format () is a static method that accepts the same arguments as the Formatter.format () method, but returns a string object. String.Format () is handy when you only need to use the Format method once.
Package Com.tomhu.format; Public class FormatTest4 { publicstaticvoid main (string[] args) { int age =; = "Huhx"; = String.Format ("My name is%s and my age is%d", name, age); SYSTEM.OUT.PRINTLN (info);} }
It outputs the following results:
My name is HUHX and my age is 22
In fact, the essence of the String.Format method is still Formatter.format (), but only to do a simple package:
Public Static string Format (string format, Object ... args) { returnnew Formatter (). Format ( Format, args). ToString ();}
Simple 16-Binary conversion tool
PackageCom.tomhu.format; Public classFORMATTEST5 { Public StaticString Format (byte[] data) {StringBuilder Builder=NewStringBuilder (); intn = 0; for(byteb:data) { if(n%16 = = 0) {builder.append (String.Format ("%05x:", N)); } builder.append (String.Format ("%02x", b)); N++; if(n% 16 = = 0) {builder.append ("\ n"); }} builder.append ("\ n"); returnbuilder.tostring (); } Public Static voidMain (string[] args) {string string= "My name is HUHX, welcome to my Blog"; SYSTEM.OUT.PRINTLN (Format (string.getbytes ())); }}
The output results are as follows:
00000:6D 6e 6d 65 20 69 73 20 68 75 68 78
Friendship Link
Java Foundation----formatted output of >java