PrintWriter format(String format, Object... args)
描述 (Description)
java.io.PrintWriter.format()方法使用指定的格式字符串和参数将格式化的字符串写入此writer。 如果启用了自动刷新,则调用此方法将刷新输出缓冲区。
声明 (Declaration)
以下是java.io.PrintWriter.format()方法的声明。public PrintWriter format(String format,Object... args)
参数 (Parameters)format - 格式字符串语法中描述的格式字符串。
args - 格式字符串中格式说明符引用的参数。 如果参数多于格式说明符,则忽略额外参数。 参数的数量是可变的,可以为零。 参数的最大数量受Java虚拟机规范定义的Java数组的最大维数限制。 null参数的行为取决于转换。
返回值 (Return Value)
此方法返回此writer。
异常 (Exception)IllegalFormatException - 如果格式字符串包含非法语法,格式说明符与给定参数不兼容,给定格式字符串的参数不足或其他非法条件。
NullPointerException - 如果格式为null。
例子 (Example)
以下示例显示了java.io.PrintWriter.format()方法的用法。package com.iowiki;
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