Why the output is incomplete when Java writes a file, and how to resolve it close () or flush ()

Source: Internet
Author: User

In the Java IO Architecture, writing a file usually uses the following statement

BufferedWriter bw=new BufferedWriter (New FileWriter ("SQL statement. txt"));

Use this when you must not forget his partner code.

Bw.close ();

Or

Bw.flush ();


In fact, when writing a file, FileWriter stores the content in a buffer, and when the buffer is full, the contents of the buffer are written to the file, the contents continue to be stored in the buffer, and the flush () forces the contents of the memory to be written to the file, even if the memory is not full. This is why the final call to Filewriter.close (), the Close () method, calls Flush (), so it can. Otherwise, there will be a small portion of the content missing at the end. Especially when writing small files, the file will appear blank, no content.
This problem is very common and deserves attention.

As can be seen in the heavy source code, flush () automatically calls close ()

    public void Close () throws IOException {        try {          flush ();        } catch (IOException ignored) {        }        out.close ( );    }

  

Why the output is incomplete when Java writes a file, and how to resolve it close () or flush ()

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.