void close()
描述 (Description)
java.util.Formatter.close()方法关闭此格式化程序。 如果目标实现Closeable接口,则将调用其close方法。 关闭格式化程序允许它释放它可能持有的资源(例如打开的文件)。 如果格式化程序已关闭,则调用此方法无效。
声明 (Declaration)
以下是java.util.Formatter.close()方法的声明
public void close()
参数 (Parameters)
NA
返回值 (Return Value)
此方法不返回值。
异常 (Exception)
NA
例子 (Example)
以下示例显示了java.util.Formatter.close()方法的用法。
package com.iowiki;
import java.util.Formatter;
import java.util.Locale;
public class FormatterDemo {
public static void main(String[] args) {
// create a new formatter
StringBuffer buffer = new StringBuffer();
Formatter formatter = new Formatter(buffer, Locale.US);
// format a new string
String name = "World";
formatter.format("Hello %s !", name);
// print the formatted string
System.out.println("" + formatter);
// close the formatter
formatter.close();
// attempt to access the formatter results in exception
System.out.println("" + formatter);
}
}
让我们编译并运行上面的程序,这将产生以下结果 -
Hello World !
Exception in thread "main" java.util.FormatterClosedException
at java.util.Formatter.ensureOpen(Formatter.java:2318)
at java.util.Formatter.toString(Formatter.java:2265)
at java.lang.String.valueOf(String.java:2826)
at java.lang.StringBuilder.append(StringBuilder.java:115)
at com.iowiki.FormatterDemo.main(FormatterDemo.java:25)
Java Result: 1