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


Java Formatter flush()用法及代码示例


flush()方法是刷新格式化程序的java.util.Formatter的内置方法。将任何缓冲的输出在其目标位置写入基础操作系统称为刷新。

用法

public void flush()

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


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

错误和异常:关闭格式化程序后使用此函数时,该函数将引发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()



相关用法


注:本文由纯净天空筛选整理自gopaldave大神的英文原创作品 Formatter flush() method in Java with Examples。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。