flush() just makes sure that any buffered data is written to disk (in this case - more generally, flushed through whatever IO channel you're using). You can still write to the stream (or writer) afterwards.

close() flushes the data and indicates that there isn't any more data. It closes any file handles, sockets or whatever. You then can't write to the stream (or writer) any more.

Note that without calls to flush() data can still be written to the IO channel in question - it's just that some data might be buffered.

close() generally calls flush() as well, but it's recently been pointed out to me that in some JDK implementations, any exceptions thrown by flushing as part of closing are swallowed :(

Answer from Jon Skeet on Stack Overflow
🌐
GeeksforGeeks
geeksforgeeks.org › java › printwriter-flush-method-in-java-with-examples
PrintWriter flush() method in Java with Examples - GeeksforGeeks
October 24, 2025 - Note: Calling flush() does not close the stream; it simply ensures that all buffered content is written out. ... import java.io.PrintWriter; class GFG{ public static void main(String[] args){ String str = "GeeksForGeeks"; try { // Create a ...
Discussions

[Java] Why is FileWriter.close() so important?
Some answers here are just plain wrong I'm afraid. If you don't close your streams / writes the underlying lock on the file won't be released by the JVM. However, when the JVM finishes, the OS sees the process is finished and will release any locks that process had on the file-handles. So the situation that the lock will remain will only exist if a Java process somehow ends up in a 'zombie' state where it won't terminate but also won't release the locks. This is possible; but rare. Releasing file handles is a best practice for a reason: if you implement something you know best when you're 'done' with a file. The sooner you release a file handle the sooner other processes can use it, and these handles are resources for which is there a limited supply. In additional; while multiple processes can read the same file, only a single one can write to it. Aside from all that; when you close a stream any contents that may be in a buffer also get flushed and written. This is another (smaller) reason you want to close it. You can also .flush() it yourself. You should look into try with resources : that way your resource will automatically close when you're done with it. This is considered a best practice you should make second nature. More on reddit.com
🌐 r/learnprogramming
6
7
November 20, 2019
Difference between close and Flush | Selenium Forum
Difference between close and Flush .What is the difference between close() and Flush().I have googled for the answer but did not get the satisfactory answer can More on qtpselenium.com
🌐 qtpselenium.com
January 28, 2016
"flush on outputstream will do nothing" - Oracle Forums
For appeals, questions and feedback about Oracle Forums, please email oracle-forums-moderators_us@oracle.com. Technical questions should be asked in the appropriate category. Thank you More on forums.oracle.com
🌐 forums.oracle.com
October 2, 2010
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
🌐
Baeldung
baeldung.com › home › java › java io › difference between flush() and close() in java filewriter
Difference Between flush() and close() in Java FileWriter | Baeldung
July 6, 2024 - The flush() method is primarily used to force any buffered data to be written immediately without closing the FileWriter, while the close() method both performs flushing and releases associated resources.
🌐
Educative
educative.io › answers › what-is-the-writerclose-method-in-java
What is the writer.close() method in Java?
We use try and catch to catch any errors (if errors are thrown). The writer uses the write() method to write. It then uses append() to append strings to the writer, flush() flushes the writer, and we close the writer.
🌐
Coderanch
coderanch.com › t › 487134 › certification › Function-close-flush-methods
Function of close() and flush() methods.. (OCPJP forum at Coderanch)
Flush makes sure that there is nothing waiting to be written to the file (this is the same reason you don't get any output if you don't use flush). close method flushes the stream and then close it so you cannot write anything else to the stream... SCJP 6 | SCWCD 5 | Javaranch SCJP FAQ | SCWCD Links
🌐
GeeksforGeeks
geeksforgeeks.org › java › writer-flush-method-in-java-with-examples
Writer flush() method in Java with Examples - GeeksforGeeks
July 11, 2025 - The flush() method of Writer Class in Java is used to flush the writer. By flushing the writer, it means to clear the writer of any element that may be or maybe not inside the writer. It neither accepts any parameter nor returns any value.
Find elsewhere
🌐
Reddit
reddit.com › r/learnprogramming › [java] why is filewriter.close() so important?
r/learnprogramming on Reddit: [Java] Why is FileWriter.close() so important?
November 20, 2019 -

I'm learning how to read from and write to programs right now, and just spent more time than I would like to admit trying to figure out why my code wouldn't work. I forget to include FileWriter.close() at the end of my function. This has happened many times since the start of this section of learning java.

Why is it so important? Shouldn't a FileWriter "close" when the program ends? Like the FileWriter literally won't properly write to a file unless I include the call to this method, even when including a seemingly more important method call (i.e. FileWriter.write("foobar"))

if it makes any difference, this is the class I'm working in: https://pastebin.com/73hrSjtP

Top answer
1 of 2
2
Some answers here are just plain wrong I'm afraid. If you don't close your streams / writes the underlying lock on the file won't be released by the JVM. However, when the JVM finishes, the OS sees the process is finished and will release any locks that process had on the file-handles. So the situation that the lock will remain will only exist if a Java process somehow ends up in a 'zombie' state where it won't terminate but also won't release the locks. This is possible; but rare. Releasing file handles is a best practice for a reason: if you implement something you know best when you're 'done' with a file. The sooner you release a file handle the sooner other processes can use it, and these handles are resources for which is there a limited supply. In additional; while multiple processes can read the same file, only a single one can write to it. Aside from all that; when you close a stream any contents that may be in a buffer also get flushed and written. This is another (smaller) reason you want to close it. You can also .flush() it yourself. You should look into try with resources : that way your resource will automatically close when you're done with it. This is considered a best practice you should make second nature.
2 of 2
1
Shouldn't a FileWriter "close" when the program ends? Yes. But it sometimes happens that your program doesn't 'end' normally or that closing won't work. For example a few ways that this can fail: Your program crashed (in this case whatever wasn't already written will not be written to the file). Your program gets killed for some reaosn (the user does it explicitly, or the operating system does so implicitly for some reason, for example if your program stalls for too long, it is often killed automatically or in response to a user pressing a button in a "this application is not responding" dialog). The computer lost power completely (hard power off). The user closed the laptop lid (before you called close) and the laptop went to sleep. In general this is OK, but maybe later on the battery gets completely drained, so it will never wake up. This is pretty much equivalent to the above situation (losing power completely). The user closed the laptop lid (going to sleep), but something strange happens when you open it up again later and the system can't restore everything (usually it works but sometimes this happens as well), so it means that your program will effectively be crashed or killed. There is not enough space on the device (so that when you call close it will fail, but if you never do it yourself, you will never realize there is a problem). In practice you might rely on closing a file automatically, but for very important data, you might consider closing and verifying that it actually worked (e.g. if closing failed it could mean that there is no more space on the drive). The minimum you should do in such a situation is to print a message to inform the user that the saving operation failed.
🌐
TutorialsPoint
tutorialspoint.com › article › what-is-the-use-of-in-flush-and-close-methods-of-bufferedwriter-class-in-java
What is the use of in flush() and close() methods of BufferedWriter class in Java?
August 1, 2019 - The flush() method is used to push the contents of the buffer to the underlying Stream. In the following Java program, we are trying to print a line on the console (Standard Output Stream).
🌐
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.
🌐
qtpselenium
qtpselenium.com › selenium-training › forum › difference-between-close-and-flush-632
Difference between close and Flush | Selenium Forum
January 28, 2016 - Flush() is a java function which is used to write files. close() is a selenium webdriver function which closes the web browser they have nothing in common. M Replied on 04/02/2016 · While i invoke bufferewriter,say for example,.. Bufferewriter ...
🌐
Blogger
javarevisited.blogspot.com › 2014 › 10 › right-way-to-close-inputstream-file-resource-in-java.html
Right way to Close InputStream and OutputStream in Java - Example
Bottom line is all opened streams must be closed once you are through with them. This rule applies to all resources like database connections, network connections, files, printers and any other shared resource. You must release once you are done. Other Java File Tutorials and Examples If you like this article and love to read more about InputStream, Files and OutputStream in Java, see these amazing articles : Difference between FileInputStream and FileReader in Java
🌐
Oracle
forums.oracle.com › ords › apexds › post › flush-on-outputstream-will-do-nothing-4509
"flush on outputstream will do nothing" - Oracle Forums
October 2, 2010 - Hello, as stated in the api: http://download.oracle.com/javase/1.4.2/docs/api/java/io/OutputStream.html#flush() the method flush does nothing on outputstream, but what does this exactly means? if ...
🌐
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
🌐
O'Reilly
oreilly.com › library › view › java-i-o › 1565924851 › ch02s04.html
Flushing and Closing Output Streams - Java I/O [Book]
March 16, 1999 - This should happen when the program exits or when you explicitly invoke the close() method: ... For example, again assuming out is an OutputStream of some sort, calling out.close() closes the stream and implicitly flushes it.
Author   Elliotte Rusty Harold
Published   1999
Pages   600
🌐
Javadeploy
javadeploy.com › java streams › writing data using streams › java i/o flush
Java I/O Flushing | Closing (Classic Streams)
If you only use a stream for a short time, you do not need to flush it explicitly. It should be flushed when the stream is closed. Of course this requires you to actually call the close() method instead, but generally you do not need to call both close() and flush().
🌐
Quora
quora.com › Why-do-we-have-to-close-FileWriter-in-Java-How-does-FileWriter-work
Why do we have to close() FileWriter in Java? How does FileWriter work? - Quora
Answer (1 of 3): The big concept here is the ‘external resource’. When you’re working with files in any language, you work closely with the operating system of that machine. The OS is responsible for restricting access to files and keeping them free from corruption.
🌐
Oracle
forums.oracle.com › ords › apexds › post › flushing-outputstream-4503
Flushing OutputStream - Oracle Forums
August 8, 2008 - Greetings & Salutations, I'm beginning Java programming and have a question. What does the flush() method of OutputStream really provide and is it necessary to call? Can the call be omitted? I loo...
🌐
Tutorialspoint
tutorialspoint.com › java › io › bufferedwriter_flush.htm
Java - BufferedWriter flush() method
Does Not Close the Writer− Unlike the close() method, flush() keeps the writer open for further use. Use Cases− Useful in scenarios where you want to ensure data is written without closing the writer, such as logging, writing intermediate ...
🌐
Baeldung
baeldung.com › home › persistence › jpa › correct use of flush() in jpa
Correct Use of flush() in JPA | Baeldung
March 12, 2025 - It provides methods for managing ... and performing CRUD operations on the database. The flush() method is used to synchronize any changes made to entities managed by persistence context with the underlying database. When we invoke flush() on the EntityManager, the JPA provider in turn executes any SQL statements required to persist or update the entities in the database. Before delving further into the correct use of this method, let’s take a look at a concept that is closely related to ...