void flush


描述

The java.io.BufferedInputStream.flush() method flushes the buffered output bytes to write out to the underlying output stream.

声明

以下是java.io.BufferedOutputStream.flush()方法的声明。

public void flush()

参数

NA

返回值

该方法没有返回值

异常

IOException − 如果发生I / O错误。

实例

以下示例显示了java.io.BufferedOutputStream.flush()方法的用法。

package com.tutorialspoint;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.ByteArrayOutputStream;
import java.io.FileInputStream;
import java.io.IOException;

public class BufferedOutputStreamDemo {
   public static void main(String[] args) throws Exception {
      FileInputStream is = null;
      BufferedInputStream bis = null;
      ByteArrayOutputStream baos = null;
      BufferedOutputStream bos = null;

      try {
         // open input stream test.txt for reading purpose.
         is = new FileInputStream("c:/test.txt");

         // input stream is converted to buffered input stream
         bis = new BufferedInputStream(is);

         // creates a new byte array output stream
         baos = new ByteArrayOutputStream();

         // creates a new buffered output stream to write 'baos'
         bos = new BufferedOutputStream(baos);

         int value;

         // the file is read to the end
         while ((value = bis.read()) != -1) {
            bos.write(value);
         }

         // invokes flush to force bytes to be written out to baos
         bos.flush();

         // every byte read from baos
         for (byte b: baos.toByteArray()) {

            // converts byte to character
            char c = (char)b;
            System.out.print(c);
         }
      } catch(IOException e) {
         // if any IOException occurs
         e.printStackTrace();
      } finally {
         // releases any system resources associated with the stream
         if(is!=null)
            is.close();
         if(bis!=null)
            bis.close();
         if(baos!=null)
            baos.close();
         if(bos!=null)
            bos.close();
      }
   }
}

假设我们有一个文本文件c:/test.txt,它具有以下内容。此文件将用作示例程序的输入

ABCDEFGHIJKLMNOPQRSTUVWXYZ

让我们编译并运行上面的程序,这将产生以下结果

ABCDEFGHIJKLMNOPQRSTUVWXYZ