Java Formatter flush()方法及示例

Java Formatter flush()方法及示例

flush() 方法是 java.util.Formatter 的一个内置方法,用于冲刷formatter。将任何缓冲的输出写入其目的地的底层操作系统被称为Flushing。

语法:

public void flush()

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

返回值 :该函数没有返回任何东西,它只是刷新了格式化器。因此,返回类型为无效。

错误和异常 :当关闭格式器后使用该函数时,该函数会抛出一个 FormatterClosedException

下面是上述函数的实现。

程序 1 :

// 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

程序2

// 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://docs.oracle.com/javase/10/docs/api/java/util/Formatter.html#close()

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程