Recently, I used Java's fileoutputstream to write a file and called the flush () method.
During code review, the colleague pointed out that it is not necessary to call flush.
So I checked the source code of the fileinputstream class and found that flush () actually inherits from its parent class outputstream.
The outputstream flush () class did nothing, and suddenly realized that it was "the truth of the source code ".
In fact, flush () is the method of the flushable interface. The comment in the official document on this method is "flushes this output stream and forces any buffered output bytes to be written out .".
The outputstream method implements the flushable interface, but nothing is done. It is really confusing, so I have a misunderstanding.
So when will flush () be effective?
The answer is: When outputstream is bufferedoutputstream.
When writing a file requires the effect of flush (),
Fileoutputstream Fos = new fileoutputstream ("C: \ a.txt"); bufferedoutputstream Bos = new bufferedoutputstream (FOS );
That is to say, you need to pass fileoutputstream as a parameter of the bufferedoutputstream constructor, and then write the bufferedoutputstream to use the buffer and flush ().
View the source code of bufferedoutputstream and find that the so-called buffer is actually a byte [].
Each write of bufferedoutputstream actually writes the content to byte []. When the buffer capacity reaches the upper limit, the real disk write will be triggered.
Another method to trigger disk write is to call flush.
Google once found that there are not a few people with this misunderstanding. This article is worth remembering today.