PUBLISHED ON: MARCH 1, 2021
OutputStreamWriter flush() Method in Java
In this tutorial, we will learn about the flush() method of OutputStreamWriter class in Java. This method is available in java.io
package. It is a non-static method, it is accessible with the class object only and if we try to access the method with the class name then we will get an error. This method flushes the stream.
Syntax
This is the syntax of the flush()
method, It does not accept any parameter and the return type of the method is void, it returns nothing.
public void flush()
Example
In this example, we are creating an object of OutputStreamWriter class and we write the data to it. To flush the stream we call this method on the OutputStreamWriter.
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
class StudyTonight
{
public static void main(String[] args) throws IOException
{
try
{
OutputStream os = new FileOutputStream("E:\\studytonight\\output.txt");
OutputStreamWriter writer = new OutputStreamWriter(os);
FileInputStream in = new FileInputStream("E:\\studytonight\\output.txt");
writer.write('A');
writer.flush();
System.out.println("" + (char) in.read());
}
catch (Exception e)
{
System.out.print("Error: "+e.toString());
}
}
}
A
output.txt
A
Conclusion
In this tutorial, we learned about the OutputStreamWriter flush() method in Java. This method flushes the stream. This method is available in java.io
package. It does not accept any parameter and the return type of the method is void, it returns nothing.