Java basics ----> Java formatting output, java basics ---- formatting
In JavaSe5, the printf () format output in C language is introduced. This not only makes the control output code simpler, but also gives Java developers more control over the output format and arrangement. Today, we begin to learn about formatting output in Java.
System. out. format ()
Because the content is relatively simple, we use examples to describe it. The project structure is as follows:
The format method introduced by Java Se5 can be used for PrintStream or PrintWriter objects, including System. out objects.
Package com. tomhu. format; public class FormatTest1 {public static void main (String [] args) {int x = 5; double y = 3.141592; // The general mode is System. out. println ("x =" + x + ", y =" + y); // printf () method System. out. printf ("x = % d, y = % f \ n", x, y); // format () method System. out. format ("x = % d, y = % f \ n", x, y );}}
The output result is as follows:
x = 5, y = 3.141592x = 5, y = 3.141592x = 5, y = 3.141592
As you can see, format and printf are equivalent. They only need a simple formatted string and add 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 format code, the Formatter format method is called: formatter. format (Locale. getDefault (), format, args );
public PrintStream format(String format, Object ... args) { try { synchronized (this) { ensureOpen(); if ((formatter == null) || (formatter.locale() != Locale.getDefault())) formatter = new Formatter((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 processed by the Formatter class, and the preceding printf and format are the same. You can regard Formatter as a translator, which translates your formatted strings and data into the desired results. When you create a Formatter object, you need to pass some information to its constructor to tell it where the final result will be output.
package com.tomhu.format;import java.util.Formatter;public class FormatTest2 { public 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 ", name, age); formatter.close(); }}
The output result is as follows:
My name is huhx, and my age is 22
Format specifiers
When inserting data, if you want to control spaces 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 is 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 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 most common application is to control the minimum size of a domain, which can be achieved by specifying the width. By adding spaces when necessary, the Formatter object ensures that a domain must have at least a certain length. By default, the data is right aligned, and the alignment direction can be changed through the "-" sign.
Precision is relative to width, which is used to specify the maximum size. Width can apply various types of data conversion, and its behavior is the same. Precision is different. Not all types of data can use precision, and precision has different meanings when applied to different types of data conversion.
- When precision is applied to a String, it indicates the maximum number of output characters when the String is printed.
- When precision is applied to floating point numbers, it indicates the number of digits to display the decimal point. The default value is 6 decimal places. If the number of decimal places is too large, it is rounded. If the number is too small, it is filled with zero at the end.
- Precision cannot be applied to Integers because integers do not have decimals. If you apply precision to integers, an exception is triggered.
package com.tomhu.format;import java.util.Formatter;public class FormatTest3 { static Formatter formatter = new Formatter(System.out); public static void printTitle() { 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 void print() { 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 void main(String[] args) { printTitle(); System.out.println("----------------------------"); print(); formatter.close(); }}
The output result is as follows:
huhx linux liuli zhangkun yanzi zhangcong zhangkun yanzhou zhangcong ----------------------------My name is huhx 5 4.20My n 5 4.10
Formatter Conversion
The following table contains the most common types of conversions:
Type conversion character
D |
INTEGER (decimal) |
E |
Floating Point Number (Scientific count) |
C |
Unicode characters |
X |
INTEGER (hexadecimal) |
B |
Boolean Value |
H |
Hash code (hexadecimal) |
S |
String |
% |
Character "%" |
F |
Floating Point Number (decimal) |
|
|
String. format () is a static method that accepts the same parameters as the Formatter. format () method, but returns a String object. When you only need to use the format method once, String. format () is very convenient.
package com.tomhu.format;public class FormatTest4 { public static void main(String[] args) { int age = 22; String name = "huhx"; String info = String.format("My name is %s and my age is %d", name, age); System.out.println(info); }}
The output result is as follows:
My name is huhx and my age is 22
In fact, the essence of the String. format method is Formatter. format (), but it is a simple encapsulation:
public static String format(String format, Object... args) { return new Formatter().format(format, args).toString();}
Simple hexadecimal conversion tool
package com.tomhu.format;public class FormatTest5 { public static String format(byte[] data) { StringBuilder builder = new StringBuilder(); int n = 0; for(byte b: 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"); return builder.toString(); } public static void main(String[] args) { String string = "my name is huhx, welcome to my blog"; System.out.println(format(string.getBytes())); }}
The output result is as follows:
00000: 6d 79 20 6e 61 6d 65 20 69 73 20 68 75 68 78 2c 00010: 20 77 65 6c 63 6f 6d 65 20 74 6f 20 6d 79 20 62 00020: 6c 6f 67
Author: huhx
Source: www.cnblogs.com/huhx
Motto: you have tried your best to say that you are lucky.
Copyright: The copyright of this article is shared by the authors huhx and blog. You are welcome to repost this article. However, this statement must be retained without the author's consent and the original article link should be clearly provided on the article page; otherwise, the right to pursue legal liability will be retained.