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


描述

所述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参数的行为取决于转换。

返回值

此方法返回此writer。

异常

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

NullPointerException - 如果格式为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