Misunderstanding of the flush () method of the outputstream class

Source: Internet
Author: User

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.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.