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
🌐
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 - As we can see, after calling flush(), we can obtain the expected data by reading the file. Alternatively, we can call the close() method to transfer the buffered data to the file.
🌐
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
🌐
Javadeploy
javadeploy.com › java streams › writing data using streams › java i/o flush
Java I/O Flushing | Closing (Classic Streams) - JavaDeploy
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.
🌐
TutorialsPoint
tutorialspoint.com › 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?
import java.io.BufferedWriter; import java.io.IOException; import java.io.OutputStreamWriter; public class BufferedWriterExample { public static void main(String args[]) throws IOException { //Instantiating the OutputStreamWriter class OutputStreamWriter out = new OutputStreamWriter(System.out); //Instantiating the BufferedWriter BufferedWriter writer = new BufferedWriter(out); //Writing data to the console writer.write("Hello welcome to Tutorialspoint"); } } But, since you haven’t flushed the contents of the Buffer of the BufferedWriter nothing will be printed.
🌐
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 - (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.
🌐
Coderanch
coderanch.com › t › 276641 › java › Buffered-Writer-automatically-flush-close
Buffered Writer automatically does flush() on a close()? (I/O and Streams forum at Coderanch)
Yes, but that doesn't contradict the former comment. "Closes the stream" implies flushing it first, according to the API for any Writer. [JE]: you can see invoking BufferedWriter.close() purges the internal buffer but does not flush the associated output stream before closing it.
Find elsewhere
Top answer
1 of 4
29

Whilst close should call flush, it's a bit more complicated than that...

Firstly, decorators (such as BufferedOutputStream) are common in Java. Construction of the decorator may fail, so you need to close the "raw" stream in a finally block whose try includes the decorator. In the case of an exception, you don't usually need to close the decorator (except, for instance, for badly implemented compression decorators). You do typically need to flush the decorator in the non-exception case. Therefore:

final RawOutputStream rawOut = new RawOutputStream(rawThing);
try {
    final DecoratedOutputStream out = new DecoratedOutputStream(rawOut);
    // ... stuff with out within ...
    out.flush();
} finally {
    rawOut.close();
}

To top it, decorator close methods are often implemented incorrectly. That includes some in java.io until recently.

Of course, you probably want to use the Execute Around idiom to keep in DRY(ish).

Edit: Since Java 8 you can use try-with-resource statements that should handle everything nicely and concisely. The code will call close on each resource even if unnecessary.

try (
    RawOutputStream rawOut = new RawOutputStream(rawThing);
    DecoratedOutputStream out = new DecoratedOutputStream(rawOut)
) {
    // ... stuff with out within ...
}
2 of 4
25

Close() always flushes so no need to call.

EDIT: This answer is based on common sense and all the outputstream I encountered. Who is going to implement a close() for a buffered stream without flushing buffer first? There is no harm to call flush right before close(). However, there are consequences if flush() is called excessively. It may defeat underneath buffering mechanism.

🌐
Coderanch
coderanch.com › t › 442764 › java › fileWriter-flush
Does fileWriter.flush() is always necessary? (I/O and Streams forum at Coderanch)
April 25, 2009 - http://www.jamonapi.com/ - a fast, free open source performance tuning api. JavaRanch Performance FAQ ... steve souza wrote:Note close calls flush, so calling both is redundant. I would always call close. I'm not sure what happens in your code if an exception is thrown.
🌐
Javapractices
javapractices.com › topic › TopicAction.do
Java Practices->Always close streams
Streams represent resources which you must always clean up explicitly, by calling the close method. Some java.io classes (apparently just the output classes) include a flush method. When a close method is called on a such a class, it automatically performs a flush.
🌐
Tutorialspoint
tutorialspoint.com › java › io › outputstreamwriter_close.htm
Java - ObjectStreamWriter close() method
close() flushes any buffered characters and closes the stream. It's essential to prevent data loss and free system resources. If close() is not called, some characters may remain in the buffer and not be written to the file. The following example shows the usage of ObjectStreamWriter close() ...
🌐
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.
🌐
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
Top answer
1 of 2
40

The method flush is used to "flush" bytes retained in a buffer. FileOutputStream doesn't use any buffer, so flush method is empty. Calling it or not doesn't change the result of your code.

With buffered writers the method close call explicitly flush.

So you need to call flush when you like to write the data before closing the stream and before the buffer is full (when the buffer is full the writer starts writing without waiting a flush call).

The source code of class FileOutputStream hasn't a custom version of method flush. So the flush method used is the version of its super class OutputStream. The code of flush in OutputStream is the following

public void flush() throws IOException {
}

As you see this is an empty method doing nothing, so calling it or not is the same.

2 of 2
-1

I will write a project that download 4 or 5 files repeatedly. I will write a method(for download files) and my method will be in a loop and download files repeatedly.My method will have a code like this.

Does the close method calls flush, or do I have to use flush before closing?

I recommend to use the NIO.2 API and the try-with-resources statement. This will reduce the amount of code and takes care of flushing and closing the streams:

try (InputStream inputStream = con.getInputStream()){
    Files.copy(inputStream, Paths.get("C:\\programs\\TRYFILE.csv"));
}

The topic is a bit confusing since OutputStream.close does indeed not require an automatic flush, but subclasses might specify that. They might also provide a flush method which does nothing (e.g. as the one inherited from OutputStream, which is the case for FileOutputStream). In this case it has no effect to call the flush method, of course, so you can omit it.

If in doubt (if you don't know which subclass you're working with) I guess it's better to call the flush manually.

But again, using the code above this is taken care for you.

🌐
Tutorialspoint
tutorialspoint.com › java › io › writer_flush.htm
Java - Writer flush() method
package com.tutorialspoint; import java.io.IOException; import java.io.PrintWriter; import java.io.Writer; public class WriterDemo { public static void main(String[] args) { String s = "Hello World"; // create a new writer Writer writer = new PrintWriter(System.out); try { // append a string writer.append(s); // flush the writer writer.flush(); // append a new string in a new line writer.append("\nThis is an example"); // flush the stream again writer.close(); } catch (IOException ex) { ex.printStackTrace(); } } }
Top answer
1 of 2
4

As the javadoc says, you don't need to flush yourself. But, it's still good to do, considering your readers, and common sense.

Few experts know the javadoc by heart. I wouldn't know for sure if the stream will be flushed or not without looking it up, and I'm probably not alone. Seeing the explicit flush() call makes this perfectly clear, and therefore makes the code easier to read.

Furthermore, the method name close() implies nothing about flushing. It's from the Closeable interface, and naturally, it says nothing about flushing. If you don't flush a buffered output stream before closing, despite wanting to flush it, you'll be relying on assumptions that may or may not be true. It would weaken your implementation.

Any assumptions you make, you should somehow pass on to future maintainers. One way to do that is by leaving a comment:

// no need to flush() manually, close() will do it automatically

If you don't leave this comment, future maintainers may have to lookup the javadoc too, if like me they don't have it memorized. But then, why would you write such comment when it's easier and better to just call it yourself now and be done with it.

In short, flushing first before closing is simply following good logic. No need for assumptions and second guesses, and no need to make your readers think.

2 of 2
-1

For output, it is important that we do call flush() and close() because buffered data could be lost, as explained by the first answer here. If your program's output is smalland your writer finishes quickly, it won't make much difference to close() and flush() in my experience.

For input, it won't matter if we don't call close() before the system exits.

🌐
CodingTechRoom
codingtechroom.com › question › understanding-the-use-of-flush-before-close-in-java-streams
When Should You Use flush() Before close() in Java I/O Streams? - CodingTechRoom
OutputStream out = new FileOutputStream("example.txt"); try { out.write(data); // Explicitly flushing before closing out.flush(); } finally { out.close(); } In Java, while calling the close() method on I/O streams does indeed invoke flush(), there are specific scenarios in which explicitly ...
🌐
GeeksforGeeks
geeksforgeeks.org › java › bufferedwriter-close-method-in-java-with-examples
BufferedWriter close() method in Java with Examples - GeeksforGeeks
May 28, 2020 - The close() method of BufferedWriter class in Java is used to flush the characters from the buffer stream and then close it. Once the stream is closed further calling the methods like write() and append() will throw the exception.
🌐
Baeldung
baeldung.com › home › java › java io › closing java io streams
Closing Java IO Streams | Baeldung
January 8, 2024 - Calling the close() method invokes flush() to write the remaining data in the buffer. When we write data to a file using FileOutputStream, some operating systems such as Windows hold the file in our application.