Developer get into a habit of calling flush() after writing something which must be sent.

IMHO Using flush() then close() is common when there has just been a write e.g.

// write a message
out.write(buffer, 0, size);
out.flush();

// finished
out.close();

As you can see the flush() is redundant, but means you are following a pattern.

Answer from Peter Lawrey on Stack Overflow
🌐
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)
Close() also does a flush, so you don't necessarily need to call flush(). You should always call close(). And you should call close() in a finalize block to ensure you always call it (even if an exception is thrown). BTW, you can also use a different PrintWriter constructor that will tell ...
Discussions

Help with Java.io.PrintWriter.flush()? Also a bit of a rant.
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. More on reddit.com
🌐 r/learnjava
6
0
October 19, 2020
java - How to use flush() for PrintWriter - Stack Overflow
If you use close(), flush() is not necessary in your first and second example (except u wanna use flush before closing). On top of that your second example also flushes automatically when using the methods: println, printf, or format ... This question is fairly old and already has an accepted answer. How does your answer improve the previous accepted answer? ... The second option is better to use, as it will create an autoflushable PrintWriter ... More on stackoverflow.com
🌐 stackoverflow.com
java - What exactly is the use of flush for a printwriter object? - Stack Overflow
Usually it is not necessary to ... as close() flushes the buffer for you. ... Join us for our first community-wide AMA (Ask Me Anything) with Stack... bigbird and Frog have joined us as Community Managers ... Is it better to redirect users who attempt to perform actions they can't yet... ... 3 PrintWriter ... More on stackoverflow.com
🌐 stackoverflow.com
io - Java - Understanding PrintWriter and need for flush - Stack Overflow
Ok, firstly I apologise for all the code but I feel like too much code is better than not enough. I'm making a simple chat client and printwriter in particular i'm struggling with. With the code th... More on stackoverflow.com
🌐 stackoverflow.com
🌐
Oracle
docs.oracle.com › javase › 7 › docs › api › java › io › PrintWriter.html
PrintWriter (Java Platform SE 7 )
Flushes the stream. ... Closes the stream and releases any system resources associated with it.
🌐
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
🌐
Tabnine
tabnine.com › home page › code › java › java.io.printwriter
java.io.PrintWriter.flush java code examples | Tabnine
@Override public void dump(OutputStream output) { // Do not close this writer in order to keep output stream open. final PrintWriter p = new PrintWriter(new OutputStreamWriter(output, StandardCharsets.UTF_8)); p.printf("Dump of %s:%n", this); for (int i = 0; i < values.size(); i++) { p.printf("<%d> %s%n", i, values.get(i)); } p.flush(); } }
🌐
Educative
educative.io › answers › what-is-the-writerclose-method-in-java
What is the writer.close() method in Java?
The close() or writer.close() method is used to close the writer. close() flushes and then closes the stream. Once the stream has been closed, further write() or flush() invocations will cause an IOException to be thrown.
Find elsewhere
🌐
GeeksforGeeks
geeksforgeeks.org › java › printwriter-flush-method-in-java-with-examples
PrintWriter flush() method in Java with Examples - GeeksforGeeks
October 24, 2025 - It ensure that all data written ... does not accept any parameters. ... Note: Calling flush() does not close the stream; it simply ensures that all buffered content is written out....
🌐
Processing
processing.org › reference › printwriter_flush_
flush() / Reference / Processing.org
January 1, 2021 - Flushes the PrintWriter object. This is necessary to ensure all remaining data is written to the file before it is closed.
🌐
Oracle
docs.oracle.com › javase › 7 › docs › api › java › io › BufferedWriter.html
BufferedWriter (Java Platform SE 7 )
Flushes the stream. ... Closes the stream, flushing it first. Once the stream has been closed, further write() or flush() invocations will cause an IOException to be thrown.
🌐
O'Reilly
oreilly.com › library › view › java-i-o › 1565924851 › ch02s04.html
Flushing and Closing Output Streams - Java I/O [Book]
March 16, 1999 - For example, again assuming out is an OutputStream of some sort, calling out.close() closes the stream and implicitly flushes it. Once you have closed an output stream, you can no longer write to it.
Author   Elliotte Rusty Harold
Published   1999
Pages   600
🌐
Quora
quora.com › What-does-it-mean-to-flush-a-file-in-java
What does it mean to flush a file in java? - Quora
Those bytes/characters may remain ... BufferedWriter.flush(), OutputStream.flush(), PrintWriter.flush()) forces the buffered data to be written through to the next layer (e.g., the underlying stream/OS)....
🌐
Oracle
docs.oracle.com › javase › 8 › docs › api › java › io › PrintWriter.html
PrintWriter (Java Platform SE 8 )
March 16, 2026 - Flushes the stream. ... Closes the stream and releases any system resources associated with it.
🌐
Coderanch
coderanch.com › t › 349132 › java › close-PrintWriter-servlet
Must close PrintWriter in servlet when done? (Servlets forum at Coderanch)
February 20, 2001 - It should be closed after flush() so the PrintWriter object is elligible for garbage collection immediately.
🌐
Medium
medium.com › deepcode-ai › deepcodes-top-suggestions-3-java-missing-close-or-flush-9031d909e091
DeepCode’s Top Suggestions #3: Java missing Close or Flush | by Frank Fischer | DeepCodeAI | Medium
January 11, 2020 - In our initial example, the following things should be changed: (1) The class which owns the stream, should be responsible for closing it properly. (2) By using flush() or simply setting autoflush to true in the constructor, the class should make sure to write out data. If you are unsure about the handling open and close or flush in your code, visit https://deepcode.ai and give it a test.