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


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。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。