flush() is probably not required in your example.

What it does is ensure that anything written to the writer prior to the call to flush() is written to the underlying stream, rather than sit in some internal buffer.

The method comes in handy in several types of circumstances:

  1. If another process (or thread) needs to examine the file while it's being written to, and it's important that the other process sees all the recent writes.

  2. If the writing process might crash, and it's important that no writes to the file get lost.

  3. If you're writing to the console, and need to make sure that every message is shown as soon as it's written.

Answer from NPE on Stack Overflow
🌐
Reddit
reddit.com › r/learnjava › help with java.io.printwriter.flush()? also a bit of a rant.
r/learnjava on Reddit: Help with Java.io.PrintWriter.flush()? Also a bit of a rant.
October 19, 2020 -

So I am confused with the flush() method of the PrintWriter class. According to all documentation descriptions, it 'flushes' the stream, whatever that means. Luckily I got a better explanation somewhere else, but even then it didn't explain how I'd seen it function. GeeksforGeeks said " it means to clear the stream of any element that may be or maybe not inside the stream". Ok, so I assume that just means it empties the stream, yes?

No, that is not what it does. The given code from the GeeksforGeeks website (found here) is as follows:

// Java program to demonstrate 
// PrintWriter flush() method 
  
import java.io.*; 
  
class GFG { 
    public static void main(String[] args) 
    { 
  
        // The string to be written in the Writer 
        String str = "GeeksForGeeks"; 
  
        try { 
  
            // Create a PrintWriter instance 
            PrintWriter writer 
                = new PrintWriter(System.out); 
  
            // Write the above string to this writer 
            // This will put the string in the stream 
            // till it is printed on the console 
            writer.write(str); 
  
            // Now clear the stream 
            // using flush() method 
            writer.flush(); 
        } 
        catch (Exception e) { 
            System.out.println(e); 
        } 
    } 
} 

With output as follows:

GeeksForGeeks

Simple enough right? Well if you remove line 26 of the code above (writer.flush()) then you get no output. So that means that when you flush the input stream, it actually goes somewhere, it doesn't just get erased. So why isn't that put into the documentation and explanation?

I am upset about this whole thing and I'm annoyed that the official documentation doesn't elaborate more on what 'flush' means in the context of the method, class, etc. But aside from me being upset, I would like someone to either explain whats going on here or to link me to some documentation that actually gets it right.

Top answer
1 of 4
4
The meaning of "flush" is pretty consistent through the entire IO framework, and it isn't specific to the PrintWriter class. You can find good documentation in the base Writer class , for example: Flushes the stream. If the stream has saved any characters from the various write() methods in a buffer, write them immediately to their intended destination. Then, if that destination is another character or byte stream, flush it. Thus one flush() invocation will flush all the buffers in a chain of Writers and OutputStreams. If the intended destination of this stream is an abstraction provided by the underlying operating system, for example a file, then flushing the stream guarantees only that bytes previously written to the stream are passed to the operating system for writing; it does not guarantee that they are actually written to a physical device such as a disk drive. For example, if you are writing to a file, it is inefficient to write every single byte individually to the file; it is more efficient to write larger chunks to the file. Therefore, the FileWriter implementation might store your written bytes in some kind of buffer (such as a byte array) until it has a sufficiently large chunk to write to the file, so that it can be done efficiently. By invoking the flush() method, you can explicitly "flush" the buffer, which basically means that it take all of the bytes stored in the buffer and write them to the file/destination immediately, and clear/reset the buffer. Typically, you don't need to worry about explicitly calling flush(), as it will be done automatically when you close the writer or outputstream.
2 of 4
1
Other answers have addressed the buffer flushing so I'll comment on the example code. That implementation's leaky; doesn't directly close the writer and certainly doesn't do it in a finally block. It should use "try with resources" like this try (PrintWriter writer = new PrintWriter(System.out) { ... } https://docs.oracle.com/javase/tutorial/essential/exceptions/tryResourceClose.html
🌐
GeeksforGeeks
geeksforgeeks.org › java › printwriter-flush-method-in-java-with-examples
PrintWriter flush() method in Java with Examples - GeeksforGeeks
October 24, 2025 - Calling flush() ensures that it appears on the console immediately. ... import java.io.PrintWriter; class GFG{ public static void main(String[] args){ try { // Create a PrintWriter instance PrintWriter writer = new PrintWriter(System.out); // ...
🌐
Coderanch
coderanch.com › t › 499845 › certification › PrintWriter-flush-close-code-work
PrintWriter using flush() and close() for code to work [Solved] (OCPJP forum at Coderanch)
Calling pw.println("howdy") just gives the "howdy" data to the PrintWriter. It does not automatically write the data to the file (it buffers it). Calling flush() tells PrintWriter to write the buffered data to the file (actually it tells FileWriter to write the data to the file).
🌐
Oracle
docs.oracle.com › javase › 8 › docs › api › java › io › PrintWriter.html
PrintWriter (Java Platform SE 8 )
2 days ago - Creates a new PrintWriter, without automatic line flushing, from an existing OutputStream.
🌐
Oracle
docs.oracle.com › javase › 7 › docs › api › java › io › PrintWriter.html
PrintWriter (Java Platform SE 7 )
Creates a new PrintWriter, without automatic line flushing, from an existing OutputStream.
🌐
Processing
processing.org › reference › printwriter_flush_
flush() / Reference / Processing.org
Flushes the PrintWriter object. This is necessary to ensure all remaining data is written to the file before it is closed.
🌐
Google Groups
groups.google.com › g › comp.lang.java.help › c › bPPPDljqviY
System.out PrintWriter print() and flush() not flushing?
"Unlike the PrintStream class, if automatic flushing is enabled it will be done only when one of the println, printf, or format methods is invoked, rather than whenever a newline character happens to be output. These methods use the platform's own notion of line separator rather than the newline character." This could be part of the problem too. Maybe it would be better to use PrintStream rather than PrintWriter...
Find elsewhere
Top answer
1 of 1
4

I suspect it's because the Java authors are making assumptions about performance:

Consider the following code:

public static void printArray(int[] array, PrintWriter writer) {
    for(int i = 0; i < array.length; i++) {
        writer.print(array[i]);
        if(i != array.length - 1) writer.print(',');
    }
}

You almost certainly would not want such a method to call flush() after every single call. It could be a big performance hit, especially for large arrays. And, if for some reason you did want that, you could just call flush yourself.

The idea is that printf, format, and println methods are likely going to be printing a good chunk of text all at once, so it makes sense to flush after every one. But it would rarely, if ever, make sense flush after only 1 or a few characters.


After some searching, I have found a citation for this reasoning (emphasis mine):

Most of the examples we've seen so far use unbuffered I/O. This means each read or write request is handled directly by the underlying OS. This can make a program much less efficient, since each such request often triggers disk access, network activity, or some other operation that is relatively expensive.

To reduce this kind of overhead, the Java platform implements buffered I/O streams. Buffered input streams read data from a memory area known as a buffer; the native input API is called only when the buffer is empty. Similarly, buffered output streams write data to a buffer, and the native output API is called only when the buffer is full.

<snip>

It often makes sense to write out a buffer at critical points, without waiting for it to fill. This is known as flushing the buffer.

Some buffered output classes support autoflush, specified by an optional constructor argument. When autoflush is enabled, certain key events cause the buffer to be flushed. For example, an autoflush PrintWriter object flushes the buffer on every invocation of println or format.

🌐
Coding Shuttle
codingshuttle.com › home › handbooks › java programming handbook › java printwriter class
Java PrintWriter Class | Coding Shuttle
April 9, 2025 - PrintWriter(OutputStream out) ... PrintWriter(File file) autoFlush: If true, the output buffer is flushed automatically whenever a println, printf, or format method is called....
🌐
IncludeHelp
includehelp.com › java › printwriter-flush-method-with-example.aspx
Java PrintWriter flush() Method with Example
// Java program to demonstrate the example // of void flush() method of PrintWriter import java.io.*; public class FlushOfPW { public static void main(String[] args) { String str = "Java Programming"; // Instantiates PrintWriter PrintWriter p_stm = new PrintWriter(System.out); // Display str p_stm.println("str: " + str); // By using flush() method is to flush // the stream i.e.
🌐
Bureau of Economic Geology
beg.utexas.edu › lmod › agi.servlet › doc › detail › java › io › PrintWriter.html
: Class PrintWriter
Create a new PrintWriter from an existing OutputStream. This convenience constructor creates the necessary intermediate OutputStreamWriter, which will convert characters into bytes using the default character encoding. ... Flush the stream.
🌐
Oracle
docs.oracle.com › en › java › javase › 17 › docs › api › java.base › java › io › PrintWriter.html
PrintWriter (Java SE 17 & JDK 17)
January 20, 2026 - Creates a new PrintWriter, without automatic line flushing, from an existing OutputStream.
🌐
SourceForge
ulibgcj.sourceforge.net › javadoc › java › io › PrintWriter.html
PrintWriter
This constructor also allows "auto-flush" functionality to be specified where the stream will be flushed after every line is terminated or newline character is written. ... This method initializes a new PrintWriter object to write to the specified OutputStream.
🌐
o7planning
o7planning.org › 13411 › java-printwriter
Java PrintWriter Tutorial with Examples | o7planning.org
If BufferedWriter participates in structure of PrintWriter, data will be written temporarily to buffer (of BufferedWriter), Which will be pushed down to targert when buffer is full (See illustration above). You can proactively push data into target by calling PrintWriter.flush() method.
🌐
Scaler
scaler.com › home › topics › java class printwriter
Java Class PrintWriter - Scaler Topics
December 19, 2022 - Another benefit of using PrintWriter is that you may instruct it to automatically flush its data after each println() operation.