Skip to Content

Flush output stream

  1. /*
  2.   Flush output stream
  3.   This Java example shows how to flush output stream using flush method of
  4.   DataOutputStream class.
  5. */
  6.  
  7. import java.io.DataOutputStream;
  8. import java.io.FileOutputStream;
  9. import java.io.IOException;
  10.  
  11.  
  12. public class FlushStream {
  13.  
  14.   public static void main(String[] args) {
  15.     String strFilePath = "C://FileIO//WriteByte.txt";
  16.    
  17.     try
  18.     {
  19.       //create FileOutputStream object
  20.       FileOutputStream fos = new FileOutputStream(strFilePath);
  21.      
  22.       /*
  23.        * To create DataOutputStream object from FileOutputStream use,
  24.        * DataOutputStream(OutputStream os) constructor.
  25.        *
  26.        */
  27.      
  28.        DataOutputStream dos = new DataOutputStream(fos);
  29.      
  30.        String strContent = "This example shows how to flush output stream!";
  31.        dos.writeBytes(strContent);
  32.      
  33.        /*
  34.         * To flush output stream, use
  35.         * void flush() method of DataOutputStream class.
  36.         *
  37.         * This method internally calls flush method of underlying OutputStream
  38.         * class which forces any buffered output bytes to be written in the stream.
  39.         */
  40.        
  41.         dos.flush();
  42.        
  43.         //close the stream
  44.         dos.close();
  45.        
  46.     }
  47.     catch (IOException e)
  48.     {
  49.       System.out.println("IOException : " + e);
  50.     }
  51.  
  52.   }
  53. }

Advertisement: