Signup/Sign In

Java FilterWriter flush() Method

In this tutorial, we will learn about the flush() method in FilterWriter class. The flush() method belongs to java.io package and used to flush out the string from this FilterWriter stream. This method 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 may throw an exception at the time of flushing the stream.

Syntax

This is the syntax declaration of the flush method. This method will flush out the string.

public void flush()

enlightenedIOException: This exception may throw when getting any input/output error.

Example of the flush() Method

In the following example, we are using the flush() method to flushes out the string from the FilterWriter.

import java.io.FilterWriter;
import java.io.StringWriter;
import java.io.Writer;
public class StudyTonight
{
	public static void main(String[] args) 
	{
		try
		{
			Writer writer = new StringWriter(10);
			FilterWriter filterWriter = new FilterWriter(writer) {};
			filterWriter.write('S');
			filterWriter.write('t');
			filterWriter.write('u');
			filterWriter.write('d');
			filterWriter.write('y');
			filterWriter.flush();
			String str = writer.toString();
			System.out.println(str);
			filterWriter.flush();
		}
		catch(Exception e)
		{
			System.out.println("Exception: "+e.toString());
		}

	}
}


Study

This method is a non-static method, if we try to invoke it with the class name it will cause an error:

FilterWriter.flush();


Exception in thread "main" java.lang.Error: Unresolved compilation problem:
Cannot make a static reference to the non-static method flush() from the type FilterWriter

Conclusion

In this tutorial, we learned about the flush() method of FileWriter class in Java, which is used to flush out the string from the FileWriter stream. It is a non-static method, available in the java.io package, accessible with the class object only, trying to access it with class name will result in an error.



About the author:
I am the founder of Studytonight. I like writing content about C/C++, DBMS, Java, Docker, general How-tos, Linux, PHP, Java, Go lang, Cloud, and Web development. I have 10 years of diverse experience in software development.