Java.io.PrintWriter.format() 方法

描述

java.io.PrintWriter.format() 方法使用指定的格式字符串和参数将格式化字符串写入此编写器。 如果启用了自动刷新,则调用此方法将刷新输出缓冲区。


声明

以下是 java.io.PrintWriter.format() 方法的声明。

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

参数

  • format − 格式字符串语法中描述的格式字符串。

  • args − 格式字符串中的格式说明符引用的参数。 如果参数多于格式说明符,则忽略多余的参数。 参数的数量是可变的,可能为零。 参数的最大数量受 Java 虚拟机规范定义的 Java 数组的最大维度限制。 空参数的行为取决于转换。


返回值

此方法返回此 writer。


异常

  • IllegalFormatException − 如果格式字符串包含非法语法、与给定参数不兼容的格式说明符、给定格式字符串的参数不足或其他非法条件。

  • NullPointerException − 如果 format 为空。


示例

下面的例子展示了 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