BufferedWriter
does not write immediately write because it buffers the data it is given.
Imagine you work in the mail room at your company. Somebody walks in with a letter to send to a client. It takes you 10 minutes to go down to the post office down the street to mail it. Do you take the letter immediately, or would you wait to see if anybody else is going to bring you a letter first?
This is buffering: instead of doing an expensive operation (walking down the street) immediately, you can wait and gather lots of things to do at once - if you have 100 letters to mail, it will still take you just 10 minutes to walk down the street, even if it takes you marginally longer to stuff them in the mail box.
It's the same with IO on a computer: it's expensive. Writing to disk, sending to the network etc are slow, so you don't want to do them repeatedly if you don't have to.
But should you care that buffering is taking place? Largely, no. In the mail room example, people just want to drop off their letters, and know it will be delivered at some point in the future. And once they've dropped it off, it doesn't matter to them whether you run down the street now or wait for 100 letters first.
In code, you often don't care when the data gets written. It just gets written at some point, e.g. when the file writer is closed, or once you've asked to write a certain amount of data to the file.
If you care about the data being written before one of these things happen, you can call bw.flush()
to force it to happen immediately.
You can read more about IO and buffering in Oracle's Essential Java tutorial. You can start here, but the bit about buffering is here
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…