How to flush output stream after writing bytes

Java 8Object Oriented ProgrammingProgramming

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!
raja
Updated on 30-Jul-2019 22:30:25

Advertisements