📜  Java中的格式化程序flush()方法和示例

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

Java中的格式化程序flush()方法和示例

flush()方法是Java.util.Formatter的内置方法,用于刷新格式化程序。将其目的地中的任何缓冲输出写入底层操作系统称为刷新。

语法

public void flush()

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

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

错误和异常:在关闭格式化程序后使用此函数时,该函数会抛出FormatterClosedException

下面是上述函数的实现:

方案一:

// 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);
  
        // flushes the formatter
        frmt.flush();
        System.out.println("Flushed");
    }
}
输出:
What is your name? 
My name is Gopal Dave !
Flushed

方案二:

// Java program to implement
// the above function
  
import java.util.Formatter;
import java.util.Locale;
  
public class Main {
  
    public static void main(String[] args)
    {
        try {
            // 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);
  
            // closes the formatter
            frmt.close();
  
            // close the frmt
            frmt.flush();
            System.out.println("Flushed");
        }
        catch (Exception e) {
            System.out.println("\nException is: "
                               + e);
        }
    }
}
输出:
What is your name? 
My name is Gopal Dave !

Exception is: java.util.FormatterClosedException

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