📜  Java中的格式化程序close()方法与示例

📅  最后修改于: 2022-05-13 01:55:40.283000             🧑  作者: Mango

Java中的格式化程序close()方法与示例

close()方法是Java.util.Formatter的内置方法,用于关闭格式化程序。如果它已经关闭,它将无效。关闭它意味着它将释放它已经持有的资源。

语法

public void close()

参数:该函数不接受任何参数。

返回值:该函数不返回任何内容,它只是关闭格式化程序。因此返回类型为 void。

下面是上述函数的实现:

方案一:

// Java program to implement
// the above function
  
import java.util.Formatter;
import java.util.Locale;
  
public class Main {
  
    public static void main(String[] args)
    {
  
        // Get the string Buffer
        StringBuffer buffer = new StringBuffer();
  
        // Object creation
        Formatter frmt
            = new Formatter(buffer,
                            Locale.CANADA);
  
        // Format a new string
        String name = "My name is Gopal Dave";
        frmt.format("What is your name? \n%s !",
                    name);
  
        // Print the Formatted string
        System.out.println(frmt);
  
        // Prints the formatted string
        // again since it is not closed
        System.out.println(frmt);
  
        // close the frmt
        frmt.close();
    }
}
输出:
What is your name? 
My name is Gopal Dave !
What is your name? 
My name is Gopal Dave !

方案二:

// Java program to implement
// the above function
  
import java.util.Formatter;
import java.util.Locale;
  
public class Main {
  
    public static void main(String[] args)
    {
  
        // Get the string Buffer
        StringBuffer buffer
            = new StringBuffer();
  
        // Object creation
        Formatter frmt
            = new Formatter(buffer,
                            Locale.CANADA);
  
        // Format a new string
        String name = "Java programs are fun";
        frmt.format("%s !", name);
  
        System.out.println(frmt);
  
        // close the frmt
        frmt.close();
    }
}
输出:
Java programs are fun !

参考: https: Java/util/Formatter.html#close()