Java.io.PrintWriter.printf() 方法



描述

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

宣告

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

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

引數

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

  • format - 格式字串,如格式字串語法中所述。

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

返回值

此方法返回此寫入器。

異常

  • IllegalFormatException - 如果格式字串包含非法語法、與給定引數不相容的格式說明符、給定格式字串的引數不足或其他非法條件。有關所有可能格式錯誤的規範,請參閱格式化程式類規範的“詳細資訊”部分。

  • NullPointerException - 如果 format 為 null。

示例

以下示例顯示了 java.io.PrintWriter.printf() 方法的使用。

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);

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

         // change line
         pw.println();

         // printf text with specified locale
         // %d indicates an integer will be placed there, which is 100
         pw.printf(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
廣告