Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
284 views
in Technique[技术] by (71.8m points)

java - What exactly is the use of flush for a printwriter object?

I'm looking for a theoretical analysis. I mean, how does the buffer system works and what advantage does using flush provide? Kindly illustrate with an example, if possible.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

When you are writing to a text file, BufferedWriter does not write it to disk immediately. Instead, it keeps the data in a buffer in memory.

This has the advantage that many small writes will go into the buffer, and then the data will be written to disk in one go, ie. with one big write, instead of many small writes, which would be inefficient.

When the buffer is full, BufferedWriter will write the data out on it's own, ie. it will do the same thing as calling flush() when the buffer is full.

So when should you call flush() manually ?

  • When you need data to be on disk now. If you have a program which reads data from the file on disk at the same time it is written, you may want to ensure all of the data which is supposed to be on disk is actually there.

  • If you are writing through a network connection, you may want to call flush() so that the data gets sent through the network immediately.

Usually it is not necessary to call flush(). Just write and call close() when finished, and no need for flush() as close() flushes the buffer for you.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...