Java Formatter 類



介紹

Java Formatter 類提供對佈局對齊和調整的支援,數值、字串和日期/時間資料的常用格式,以及特定於區域設定的輸出。以下關於 Formatter 的要點:-

  • Formatter 不一定對多執行緒訪問安全。執行緒安全是可選的,由此類中方法的使用者負責。

類宣告

以下是java.util.Formatter類的宣告:-

public final class Formatter
   extends Object
   implements Closeable, Flushable

類建構函式

序號 建構函式 & 描述
1

Formatter()

此建構函式建立一個新的 formatter。

2

Formatter(Appendable a)

此建構函式使用指定的目的地建立一個新的 formatter。

3

Formatter(Appendable a, Locale l)

此建構函式使用指定的目的地和區域設定建立一個新的 formatter。

4

Formatter(File file)

此建構函式使用指定的 檔案建立一個新的 formatter。

5

Formatter(File file, String csn)

此建構函式使用指定的檔案和字元集建立一個新的 formatter。

6

Formatter(File file, String csn, Locale l)

此建構函式使用指定的檔案、字元集和區域設定建立一個新的 formatter。

7

Formatter​(File file, Charset charset, Locale l)

此建構函式使用指定的檔案、字元集和區域設定建立一個新的 formatter。

8

Formatter(Locale l)

此建構函式使用指定的區域設定建立一個新的 formatter。

9

Formatter(OutputStream os)

此建構函式使用指定的輸出流建立一個新的 formatter。

10

Formatter(OutputStream os, String csn)

此建構函式使用指定的輸出流和字元集建立一個新的 formatter。

11

Formatter(OutputStream os, String csn, Locale l)

此建構函式使用指定的輸出流、字元集和區域設定建立一個新的 formatter。

12

Formatter​(OutputStream os, Charset charset, Locale l)

此建構函式使用指定的輸出流、字元集和區域設定建立一個新的 formatter。

13

Formatter(PrintStream ps)

此建構函式使用指定的列印流建立一個新的 formatter。

14

Formatter(String fileName)

此建構函式使用指定的檔名建立一個新的 formatter。

15

Formatter(String fileName, String csn)

此建構函式使用指定的檔名和字元集建立一個新的 formatter。

16

Formatter​(String fileName, Charset charset, Locale l) 此建構函式使用指定的檔名、字元集和區域設定建立一個新的 formatter。

17

Formatter(String fileName, String csn, Locale l)

此建構函式使用指定的檔名、字元集和區域設定建立一個新的 formatter。

類方法

序號 方法 & 描述
1 void close()

此方法關閉此 formatter。

2 void flush()

此方法重新整理此 formatter。

3 Formatter format(Locale l, String format, Object... args)

此方法使用指定的區域設定、格式字串和引數將格式化的字串寫入此物件的目的地。

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

此方法使用指定的格式字串和引數將格式化的字串寫入此物件的目的地。

5 IOException ioException()

此方法返回此 formatter 的 Appendable 最後丟擲的 IOException。

6 Locale locale()

此方法返回由此 formatter 的構造設定的區域設定。

7 Appendable out()

此方法返回輸出的目的地。

8 String toString()

此方法返回對輸出的目的地呼叫 toString() 的結果。

繼承的方法

此類繼承自以下類:-

  • java.util.Object

使用 US 區域設定格式化字串示例

以下示例演示了 Java Formatter format(String, Object) 方法的使用,以使用 formatter 格式化字串。我們使用 StringBuffer 和區域設定建立了一個 formatter 物件。Formatter 用於使用 format() 方法列印字串。

package com.tutorialspoint;

import java.util.Formatter;
import java.util.Locale;

public class FormatterDemo {
   public static void main(String[] args) {

      // create a new formatter
      StringBuffer buffer = new StringBuffer();
      Formatter formatter = new Formatter(buffer, Locale.US);

      // format a new string
      String name = "World";
      formatter.format("Hello %s !", name);

      // print the formatted string 
      System.out.println(formatter);
	  
      formatter.close();
   }
}

輸出

讓我們編譯並執行上述程式,這將產生以下結果:-

Hello World !
廣告