Formatter class of java.util tools

JDK8 Online Api Chinese Manual

JDK8 Online Api English Manual

1 Formatter class

   The core of Java's support for creating formatted output is the Formatter class. This class provides format conversion function, so that we can display numbers, strings, and time and date in various ways we like. The operation mode is similar to C / C ++ 's printf () function. This class further simplifies the conversion from C / C ++ code to Java code.

1.1 Constructor of Formatter class

   Before using Formatter to format the output, a Formatter object must be created. Normally, Formatter works by converting the binary form used by the program into formatted text. Store formatted text in the buffer, whenever you need it, you can get the contents of the buffer through the program. You can let Formatter provide this buffer automatically, or you can provide it explicitly when you create the Formatter object. It is also possible for Formatter to output its own buffer to a file.
   The Formatter class defines many constructors so that Formatter objects can be constructed in various ways. Here are some of these constructors:

Formatter()
Formatter(Appendable buf)
Formatter(Appendable buf,Locale loc)
Formatter(String filename) throws FileNotFoundException
Formatter(String fileName,String charset) throws FileNotFoundException,UnsupportedEncodingException
Formatter(File outF)throws FileNotFoundException
Formatter(OutputStream outStrm)

   Among them, buf specifies the buffer for saving formatted output. If buf is null, Formatter will automatically allocate StringBuilder to save the formatted output. The parameter loc specifies the region. If no region is specified, the default region is used. The parameter filename specifies the name of the file that will be used to receive the formatted output. The charset parameter specifies the character set. If no character set is specified, the default character set is used. The parameter outF specifies a reference to the incoming file that will be used to receive the output. The parameter outStrm also specifies a reference to the output stream that will be used to receive the output. If a file is used, the output can also be written to the file.
   The most widely used constructor is probably the first one, it has no parameters. This constructor automatically uses the default region. And automatically assign StringBuilder to save the formatted output.

1.2 Methods of Formatter class

   Table 1 shows the methods defined by the Formatter class.

Table 1 Methods defined by Formatter class
method Description
void close() Close the calling Formatter object. This will cause all resources used by the Formatter object to be released. After the Formatter object is closed, it can no longer be used. If you try to use a closed Formatter object. Will cause FormatterClosedException
void flush() Refresh the formatted buffer. This causes all output currently in the buffer to be written to the target. This method is mainly used for Formatter objects bound to files
Formatter format(String fmtString,Object … args) According to the format specifier contained in fmtString, format the parameters passed by args. Return call object
Formatter format(Locale loc,String fmtString,Object … args) According to the format specifier contained in fmtString, format the parameters passed by args and use the region specified by loc for the format operation. Return call object
IOExceotion ioException() If the underlying object as the target throws an IOException, it returns the exception; otherwise, it returns null
Local Local () Returns the calling region
Appendable out() Returns a reference to the underlying object, which is the target of the output
String toString() Returns a String object containing formatted output
1.3 Basic knowledge of formatting

   After creating the Formatter object, you can use the Formatter object to create a format string. To do this, use the format () method. The most commonly used version of this method is as follows:

Formatter format(String fmtString,Object ... args)

   fmtString contains two types of entries: the first type is composed of characters that will be simply copied into the output buffer; the second type contains a format specifier, which defines the way to display subsequent parameters.
   The simplest form of a format specifier starts with a percent sign, followed by a format conversion specifier. All format conversion specifiers consist of a single character. For example, the format specifier for floating point numbers is% f. Generally, the number of parameters must be equal to the number of format specifiers, and the format specifiers and parameters are matched in order from left to right. For example, analyze the following code snippet:

Formatter fmt = new Formatter();
fmt.format("Formatting %s is easy %d %f","with Java",10,98.6);

   This code snippet creates a Formatter object containing the following string:
   Formatting with Java is easy 10 98.600000
   In this example, the format specifiers% s,% d, and% f are replaced by the parameters following the format string. Therefore,% s is replaced by "with Java",% d is replaced by 10, and% f is replaced by 98.6. All other characters simply remain unchanged. The format specifier% s specifies a string,% d specifies an integer, and% f specifies a floating-point value.
   The format specifiers that can be received by the format () method are equal and wide. Table 1 shows the titles of these formats. Note that many specifiers have both uppercase and lowercase forms. When uppercase specifiers were used, the letters were displayed in uppercase. Otherwise, uppercase and lowercase specifiers perform the same conversion. Java checks the type of each format specifier based on the corresponding parameters. If the parameters do not match, an IllegalFormatException will be thrown.

Table 2 Format specifier
Format specifier Applicable conversion Format specifier Applicable conversion
%a %A Floating point hexadecimal value % g% G Use% c or% f based on the formatted value and precision
%b %B Boolean %O Octal integer
%c character %n Insert a line break
%d Decimal integer %s %S String
%h %H The hash code of the parameter %t %T Time and date
%there is Scientific notation %x %X Hexadecimal integer
%f Decimal floating point %% Insert a% sign

   Once you have a formatted string, you can get it by calling the toString () method. For example, to continue the previous example, the following statement gets the formatted string contained in fmt:

String str = fmt.toString();

   Of course, if you just want to display the formatted string, there is no need to assign the string to the String object first. For example, when the Formatter object is passed to the println () method, the toStirng () method of the Formatter object is automatically called.
   The following short program puts all this together, and the program shows how to create and display format strings:

//A very simple example that uses Formatter.
import java.util.Formatter;
class FormatDemo {
 public static void main(String[] args) {
      Formatter fmt = new Formatter();
      fmt.format("Formatting %s is easy %d %f","with Java",10,98.6);
      System.out.println(fmt);
      fmt.close();
      /**
       * 输出:
       * Formatting with Java is easy 10 98.600000
       */
  }
}

   Another point: You can get a reference to the underlying output buffer by calling the out () method. This method returns a reference to the Appendable object.
   Now that we know the general mechanism for creating formatted strings, next we will discuss each conversion in detail, and we will describe various options, such as its, minimum field width, and precision.

1.4 Formatting strings and characters

   To format a single character, you can use% c, which will output matching character parameters without modification. To format a string, you can use% s.

1.5 Format numbers

   To format integers in decimal format, you can use% d. To format floating-point numbers in decimal format, you can use% f. To format floating-point numbers in scientific notation, you can use% e. The general form of numbers expressed in scientific notation is as follows:

x.dddddde+/-yy

   The% g format specifier causes the Formatter to use% f or% e based on the formatted value and precision. The default precision value is 6. The following program demonstrates the effect of% f and% e format specifiers:

//Demonstrate the %f and %e format specifiers.
import java.util.Formatter;
class FormatDemo2 {
 public static void main(String[] args) {
      Formatter fmt = new Formatter();
      for (double i=1.23;i<1.0e+6;i*=100){
          fmt.format("%f %e",i, i);
          System.out.println(fmt);
      }
      fmt.close();
  }
  /**
   * 输出:
   * 1.230000  1.230000e+00
   * 1.230000  1.230000e+00 123.000000  1.230000e+02
   * 1.230000  1.230000e+00 123.000000  1.230000e+0212300.000000  1.23
   */
}

   By using% o and% x, integers can be displayed in octal or hexadecimal. For example, the following line of code:

fmt.format("Hex: %x,Octal: %o",196,196)

   The output produced:

Hex: c4,Octal: 304

   By using% a, you can display floating-point values ​​in hexadecimal format. At first glance, the format generated by% a looks a bit strange. This is because% a uses a representation similar to scientific notation, including a hexadecimal base and a decimal exponent (which is a power of 2). The general form is as follows:

Ox1.sigperp

   Among them, sig contains the decimal part of the base, exp contains the exponent, p is just followed by the exponent. For example, the following call:

fmt.format("%a",512.0);

   The generated output is as follows:

0x1.0p9
1.6 Format time and date

   The more powerful conversion specifier is% t. It can format date and time information. The% t specifier works a little differently from other specifiers because it requires the use of suffixes to describe the expected components and precise format of time and date. Table 3 shows these suffixes. For example, to display minutes, you need to use% tM. Here, M indicates that minutes are displayed in a two-character width field. The parameters of the% t object must be Calendar, Date, Long, or long.

Table 3 Time and date format suffix
suffix Replace content
a Week name abbreviation
A Full name of week
b Month abbreviation
B Full name of month
c Standard date and time strings, format: day month day hour: minute: second time zone year
C The first two digits of the year
d Decimal format of monthly date (01-31)
D Month / day / year
e Decimal format of monthly date (1-31)
F year month day
h Month abbreviation
H Hour (00-23)
I (uppercase i) Hour (01-12)
j Decimal format for each year's date (001-366)
k Hour (0-23)
l (lowercase L) Hour (1-12)
L Milliseconds (000-999)
m Decimal format of month (01-13)
M Minute decimal format (00-59)
N Nanoseconds (000000000-999999999)
P AM or PM representing local time in lower case
Q The number of milliseconds since January 1, 1970
r Hours: minutes: seconds (12 hour format)
R Hours: minutes: seconds (24 hour format)
S Seconds (00-60)
s The number of milliseconds since January 1, 1970 (UTC)
T Hours: minutes: seconds (24-hour format)
and Express the year in decimal (00-99), excluding the century part (i.e. the first two digits of the year)
AND Year in decimal (0001-9999), including century
from Time difference relative to UTC
FROM Time zone name

   The following program demonstrates various formats:

//Formatting time and date
import java.util.Calendar;
import java.util.Formatter;
class TimeDateFormat {
 public static void main(String[] args) {
      Formatter fmt = new Formatter();
      Calendar cal = Calendar.getInstance();
      //Display standard 12-hour time format.
      fmt.format("%tr",cal);
      System.out.println(fmt);
      fmt.close();
      //Display complete time and date information.
      fmt = new Formatter();
      fmt.format("%tc",cal);
      System.out.println(fmt);
      fmt.close();
      //Display just hour and minute.
      fmt = new Formatter();
      fmt.format("%tl:%tM",cal,cal);
      System.out.println(fmt);
      fmt.close();
      //Display month by name and number.
      fmt = new Formatter();
      fmt.format("%tB %tb %tm",cal,cal,cal);
      System.out.println(fmt);
      fmt.close();
      /**
       * 输出:
       * 03:39:42 下午
       * 星期日 二月 09 15:39:42 CST 2020
       * 3:39
       * 二月 二月 02
       */
  }
}
1.7% n and %% specifiers

   The% n and %% format specifiers are different from other specifiers, they do not match the parameters. Instead, they are just escape sequences inserted into the output sequence. % n inserts a newline character and %% inserts a percent sign. Whether these two characters can not be directly input into the format string, of course, you can also use the standard escape sequence \ n to embed a newline character.
   The following is an example demonstrating% n and %% format specifiers:

//Demonstrate the %n and %% format specifiers.
import java.util.Formatter;
class FormatDemo3 {
 public static void main(String[] args) {
      Formatter fmt = new Formatter();
      fmt.format("Copying file%nTransfer is %d%% complete",88);
      System.out.println(fmt);
      fmt.close();
      /**
       * 输出:
       * Copying file
       * Transfer is 88% complete
       */
  }
}
1.8 Specify the minimum field width

   The% symbol and the integer before the format conversion code are used as the minimum field width specifier. This fills the output with spaces to ensure that the output reaches a specific minimum length. Even if the string or number is longer than the minimum width, it will still be output completely. By default, spaces are used for padding. If you want to use 0 for padding, you can put a 0 before the field width specifier. For example,% 05d uses 0 to fill in numbers with a total length less than 5, so that the total length of the number is 5. The field width specifier can be used for all format specifiers except% n.
   The following program demonstrates the minimum field width specifier applied to the% f conversion:

//Demonstrate a field-width specifier.
import java.util.Formatter;
class FormatDemo4 {
  public static void main(String[] args) {
       Formatter fmt = new Formatter();
       fmt.format("|%f|%n|%12f|%n|%012f|",10.12345,10.12345,10.12345);
       System.out.println(fmt);
       fmt.close();
       /**
        * 输出:
        * |10.123450|
        * |   10.123450|
        * |00010.123450|
        */
   }
}

   第1行默认宽度显示数字10.12345。第2行以12个字符宽度显示数字。第3行以12字符宽度显示数字,不过使用前导0进行填充。
   最小字段宽度修饰符经常用于产生对其的表格。例如,下面的程序生成一个表格,用来显示1到10之间数字的平方和立方:

//Create a table of squares and cubes.
import java.util.Formatter;
class FieldWidthDemo {
    public static void main(String[] args) {
        Formatter fmt;
        for(int i=1;i<=10;i++){
            fmt=new Formatter();
            fmt.format("%4d %4d %4d",i,i*i,i*i*i);
            System.out.println(fmt);
            fmt.close();
        }
        /**
         * 输出:
         *    1    1    1
         *    2    4    8
         *    3    9   27
         *    4   16   64
         *    5   25  125
         *    6   36  216
         *    7   49  343
         *    8   64  512
         *    9   81  729
         *   10  100 1000
         */
    }
}
发布了59 篇原创文章 · 获赞 20 · 访问量 3632

Guess you like

Origin blog.csdn.net/qq_34896730/article/details/104232672