The flush() method in the PrintWriter class is used to clear the stream of any characters that may be buffered. It ensure that all data written to the PrintWriter is actually sent to the destination (console, file, or network) without waiting for the buffer to fill.
Syntax
public void flush()
- Parameters: This method does not accept any parameters.
- Return Type: void (does not return any value)
Note: Calling flush() does not close the stream; it simply ensures that all buffered content is written out.
Examples of flush() Method
Example 1: Writing a String to Console
import java.io.PrintWriter;
class GFG{
public static void main(String[] args){
String str = "GeeksForGeeks";
try {
// Create a PrintWriter instance
PrintWriter writer = new PrintWriter(System.out);
// Write string to the stream
writer.write(str);
// Flush the stream to ensure immediate output
writer.flush();
} catch (Exception e) {
System.out.println(e);
}
}
}
Output
GeeksForGeeks
Explanation: Here, the string "GeeksForGeeks" is first written to the stream. Calling flush() ensures that it appears on the console immediately.
Example 2: Writing a Character to Console
import java.io.PrintWriter;
class GFG{
public static void main(String[] args){
try {
// Create a PrintWriter instance
PrintWriter writer = new PrintWriter(System.out);
// Write a character to the stream
writer.write(65); // ASCII value of 'A'
// Flush the stream to ensure immediate output
writer.flush();
} catch (Exception e) {
System.out.println(e);
}
}
}
Output
A
Explanation: The integer 65 corresponds to the ASCII value of 'A'. After writing it to the stream, flush() ensures it is printed on the console immediately.
Why Use flush()?
- Ensures immediate output of buffered data.
- Useful in interactive applications or real-time logging.
- Prevents loss of data in case of program interruption.