How to flush output stream after writing bytes


Let us first crate OutputStream with file input.txt −

FileOutputStream fileStream = new FileOutputStream("E:/input.txt");
DataOutputStream dataStream = new DataOutputStream(fileStream);

Now, the writeBytes() method writes out the string to the underlying output stream as a sequence of bytes.

dataStream.writeBytes("Demo text!");

Flush the output stream −

dataStream.flush();

The following is an example. Here, our file is “E:/input.txt” and at the end we are flushing the output stream −

Example

import java.io.DataOutputStream;
import java.io.FileOutputStream;
public class Demo {
   public static void main(String[] args) throws Exception {
      FileOutputStream fileStream = new FileOutputStream("E:/input.txt");
      DataOutputStream dataStream = new DataOutputStream(fileStream);
      dataStream.writeBytes("Demo text!");
      dataStream.flush();
      dataStream.close();
   }
}

The output is as follows i.e. the text in the file is −

Output

Demo text!

karthikeya Boyini
karthikeya Boyini

I love programming (: That's all I know

Updated on: 30-Jul-2019

340 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements