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


Java BufferedOutputStream flush()用法及代碼示例


Java中BufferedOutputStream類的flush()方法用於刷新緩衝的輸出流。此方法用於強製將緩衝輸出的字節寫出到主輸出流。

用法:

public void flush() 
            throws IOException

指定者:該方法由Flushable接口中的flush()方法指定。

覆蓋:此方法覆蓋FilterOutputStream類中的flush()方法。

參數:此方法不接受任何參數。



返回值:此方法不返回任何值。

異常:如果發生I /O錯誤,則此方法將引發IOException。

以下示例程序旨在說明IO包中BufferedOutputStream類中的flush()方法:

程序1:

// Java program to illustrate 
// BufferedOutputStream flush() method 
import java.io.*; 
public class GFG { 
    public static void main(String[] args) throws Exception 
    { 
  
        // Create byteArrayOutputStream 
        ByteArrayOutputStream 
            byteArrayOutStr 
            = new ByteArrayOutputStream(); 
  
        // Convert outputStream to 
        // bufferedInputStream 
        BufferedOutputStream buffOutputStr 
            = new BufferedOutputStream( 
                byteArrayOutStr); 
  
        // Creating byte array 
        byte b[] = { 71, 69, 69, 75, 83 }; 
        buffOutputStr.write(b); 
  
        // flush is called 
        // to compel bytes to be 
        // written out to buffOutputStr 
        buffOutputStr.flush(); 
  
        for (byte by:byteArrayOutStr 
                           .toByteArray()) { 
  
            // Converts byte to character 
            char ch = (char)by; 
            System.out.print(ch); 
        } 
    } 
}
輸出:
GEEKS

程序2:

// Java program to illustrate 
// BufferedOutputStream flush() method 
import java.io.*; 
public class GFG { 
    public static void main(String[] args) throws Exception 
    { 
  
        // Create byteArrayOutputStream 
        ByteArrayOutputStream byteArrayOutStr = new ByteArrayOutputStream(); 
  
        // Convert outputStream to 
        // bufferedInputStream 
        BufferedOutputStream buffOutputStr 
            = new BufferedOutputStream( 
                byteArrayOutStr); 
  
        // Creating first byte array 
        byte b1[] = { 71, 69, 69, 75, 83 }; 
        buffOutputStr.write(b1); 
  
        // flush is called 
        // to compel bytes to be 
        // written out to buffOutputStr 
        buffOutputStr.flush(); 
  
        // Creating second byte array 
        byte b2[] = { 70, 79, 82 }; 
        buffOutputStr.write(b2); 
  
        buffOutputStr.flush(); 
  
        buffOutputStr.write(b1); 
  
        buffOutputStr.flush(); 
  
        for (byte by:byteArrayOutStr.toByteArray()) { 
            // Converts byte to character 
            char ch = (char)by; 
            System.out.print(ch); 
        } 
    } 
}
輸出:
GEEKSFORGEEKS

參考文獻:
https://docs.oracle.com/javase/10/docs/api/java/io/BufferedOutputStream.html#flush()




相關用法


注:本文由純淨天空篩選整理自pp_pankaj大神的英文原創作品 BufferedOutputStream flush() method in Java with Examples。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。