Summary of buffer issues

ask:

If the buffer is full, but there are still characters read into the buffer, and you forget to use the flush() method to output, will it be output automatically? Or will buffer overwrite occur?

answer:

No, the cache actually disappears after shutdown.
Flush() is to forcibly output the data in the buffer (be careful not to confuse it with frush()), which is
mainly used in IO, that is, to clear the buffer data. Generally, when reading and writing streams, the data is first After reading the data into the memory, write the data to the file. When you finish reading the data, it does not mean that your data has been written, because some of it may remain in the buffer of the memory. At this time, if you call the close() method to close the read-write stream, then this part of the data will be lost, so you should flush() before closing the read-write stream.
There is also the official documentation of the buffer zone, which states that his space is large enough for us to use


ask:

What if the program keeps starting up without shutting down? Is there a default size for the buffer?

answer:

Yes, just like writing word without saving and shutting down


ask:

Before executing the close() method, the system will also implicitly execute a flush() operation, right?

answer:

If you don’t write full data, you won’t be flushed. At this time, it will happen that your data is not written successfully without flush. It will execute flush by default only when it is full of data. This is also why io adds buffers. It is to improve efficiency.

Simply put, in order to prevent multiple operations of IO (operating IO takes CPU time), a buffer is provided. When the buffer is full, the file is written again, thereby improving efficiency. Therefore, if the buffer is not full, it must be forced to output to the file, that is, flush() is called.

Guess you like

Origin blog.csdn.net/qq_43511405/article/details/108328626