Java.io.BufferedOutputStream.flush() Method

Advertisements


Description

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

Declaration

Following is the declaration for java.io.BufferedOutputStream.flush() method

public void flush()

Parameters

  • NA

Return Value

This method does not return any value.

Exception

  • IOException -- -- if an I/O error occurs.

Example

The following example shows the usage of java.io.BufferedOutputStream.flush() method.

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();
      }	
   }
}

Assuming we have a text file c:/test.txt, which has the following content. This file will be used as an input for our example program:

ABCDEFGHIJKLMNOPQRSTUVWXYZ 

Let us compile and run the above program, this will produce the following result:

ABCDEFGHIJKLMNOPQRSTUVWXYZ



Advertisements
Advertisements