當前位置: 首頁>>代碼示例 >>用法及示例精選 >>正文


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。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。