PUBLISHED ON: MARCH 4, 2021
FileWriter flush() Method in Java
In this tutorial, we will learn about the flush()
method of FileWriter class in Java. This method is used to flush the writer, which means that this method will remove all the data present inside the writer. It neither accepts any parameter nor returns any value.
Syntax
This is the syntax declaration of the flush()
method, this method does not take any parameter as input and does not return anything as its return type is void.
public void flush()
Example1: FileWriter flush()
In the following example, we are implementing how the flush()
method works, this method is used to remove the written data from the writer, here we have written the data to the writer and after that, we are flushing it by calling the flush() method.
import java.io.FileWriter;
import java.io.IOException;
class StudyTonight
{
public static void main(String[] args) throws IOException
{
try
{
FileWriter fileWriter=new FileWriter("E:\\studytonight\\output.txt");
String str = "Hello Studytonight";
fileWriter.write(str);
fileWriter.flush();
fileWriter.close();
System.out.println("Data Written to the file successfully");
}
catch(Exception e)
{
System.out.println("Error: "+e.toString());
}
}
}
Data Written to the file successfully
output.txt
Hello Studytonight
Example 2: FileWriter flush()
Here, we are implementing the example of a flush()
method to clear the writer. Once we have written the data into it we call the flush method. This method is used to flush the writer, which means that this method will remove all the data present inside the writer.
import java.io.FileWriter;
import java.io.IOException;
class StudyTonight
{
public static void main(String[] args) throws IOException
{
try
{
FileWriter fileWriter=new FileWriter("E:\\studytonight\\output.txt");
char c='A';
fileWriter.write(c);
fileWriter.flush();
fileWriter.close();
System.out.println("Data Written to the file successfully");
}
catch(Exception e)
{
System.out.println("Error: "+e.toString());
}
}
}
Data Written to the file successfully
output.txt
A
Conclusion
In this tutorial, we learned about the flush()
method of FileWriter class in Java. This method is used to flush the writer, which means that this method will remove all the data present inside the writer. It neither accepts any parameter nor returns any value.