Java.io.PrintWriter.format() 方法



描述

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

宣告

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

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

引數

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

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

返回值

此方法返回此寫入器。

異常

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

  • NullPointerException − 如果格式為 null。

示例

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

package com.tutorialspoint;

import java.io.*;

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 default locale
         // %s indicates a string will be placed there, which is s
         pw.format("This is a %s program", s);

         // change line
         pw.println();

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

© . All rights reserved.