Java.io.PrintWriter.format() 方法



描述

該 **java.io.PrintWriter.format()** 方法使用指定的格式字串和引數將格式化的字串寫入此寫入器。如果啟用了自動重新整理,則對該方法的呼叫將重新整理輸出緩衝區。

宣告

以下是 **java.io.PrintWriter.format()** 方法的宣告。

public PrintWriter format(Locale l,String format,Object... args)

引數

  • **l** − 在格式化期間應用的區域設定。如果 l 為 null,則不應用任何本地化。

  • **format** − 如格式字串語法中所述的格式字串。

  • **args** − 格式字串中格式說明符引用的引數。如果引數多於格式說明符,則忽略多餘的引數。引數的數量是可變的,可以為零。引數的最大數量受 Java 虛擬機器規範中定義的 Java 陣列的最大維度限制。對 null 引數的行為取決於轉換。

返回值

此方法返回此寫入器。

異常

  • **IllegalFormatException** − 如果格式字串包含非法的語法、與給定引數不相容的格式說明符、給定格式字串的引數不足或其他非法條件。

  • **NullPointerException** − 如果 format 為 null。

示例

以下示例演示了 **java.io.PrintWriter.format()** 方法的使用。

package com.tutorialspoint;

import java.io.*;
import java.util.Locale;

public class PrintWriterDemo {
   public static void main(String[] args) {
      String s = "Hello World";
      
      try {
         // create a new writer
         PrintWriter pw = new PrintWriter(System.out);

         // format text with specified locale.
         // %s indicates a string will be placed there, which is s
         pw.format(Locale.UK, "This is a %s program", s);

         // change line
         pw.println();

         // format text with specified locale
         // %d indicates a integer will be placed there, which is 100
         pw.format(Locale.UK, "This is a %s program with %d", s, 100);

         // flush the writer
         pw.flush();
      } catch (Exception ex) {
         ex.printStackTrace();
      }
   }
}

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

This is a Hello World program
This is a Hello World program with 100
java_io_printwriter.htm
廣告