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
广告
© . All rights reserved.