Formatter flush() method in Java with Examples
The flush() method is a built-in method of the java.util.Formatter which flushes the formatter. Writing any buffered output in its destination to the underlying operating system is referred to as Flushing.
Syntax:
public void flush()
Parameters: The function accepts no parameter.
Return Value: The function returns nothing, it just flushes the formatter. Hence the return type is void.
Errors and Exceptions: The function throws a FormatterClosedException when this function is used after closing the formatter.
Below is the implementation of the above function:
Program 1:
import java.util.Formatter;
import java.util.Locale;
public class Main {
public static void main(String[] args)
{
StringBuffer buffer = new StringBuffer();
Formatter frmt
= new Formatter(buffer,
Locale.CANADA);
String name = "My name is Gopal Dave" ;
frmt.format( "What is your name? \n%s !" ,
name);
System.out.println(frmt);
frmt.flush();
System.out.println( "Flushed" );
}
}
|
Output:
What is your name?
My name is Gopal Dave !
Flushed
Program 2:
import java.util.Formatter;
import java.util.Locale;
public class Main {
public static void main(String[] args)
{
try {
StringBuffer buffer
= new StringBuffer();
Formatter frmt
= new Formatter(buffer,
Locale.CANADA);
String name = "My name is Gopal Dave" ;
frmt.format( "What is your name? \n%s !" ,
name);
System.out.println(frmt);
frmt.close();
frmt.flush();
System.out.println( "Flushed" );
}
catch (Exception e) {
System.out.println( "\nException is: "
+ e);
}
}
}
|
Output:
What is your name?
My name is Gopal Dave !
Exception is: java.util.FormatterClosedException
Reference: https://docs.oracle.com/javase/10/docs/api/java/util/Formatter.html#close()
Last Updated :
01 Apr, 2019
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...