当前位置: 首页>>代码示例 >>用法及示例精选 >>正文


Java Java.util.Formatter.close()用法及代码示例



描述

这个java.util.Formatter.close()方法关闭此格式化程序。如果目标实现 Closeable 接口,则将调用其 close 方法。关闭格式化程序允许它释放它可能持有的资源(例如打开的文件)。如果格式化程序已经关闭,则调用此方法无效。

声明

以下是声明java.util.Formatter.close()方法

public void close()

参数

NA

返回值

此方法不返回值。

异常

NA

示例

下面的例子展示了 java.util.Formatter.close() 方法的用法。

package com.tutorialspoint;

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.tutorialspoint.FormatterDemo.main(FormatterDemo.java:25)
Java Result:1

相关用法


注:本文由纯净天空筛选整理自 Java.util.Formatter.close() Method。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。