When to flush a BufferedWriter

后端 未结 3 1928
滥情空心
滥情空心 2020-12-05 04:28

In a Java program (Java 1.5), I have a BufferedWriter that wraps a Filewriter, and I call write() many many times... The resulting file is pretty big...

Among the li

相关标签:
3条回答
  • 2020-12-05 04:48

    The ideal flushing moment is when you need another program reading the file to see the data that's been written, before the file is closed. In many cases, that's never.

    0 讨论(0)
  • 2020-12-05 04:49

    The BufferedWriter will already flush when it fills its buffer. From the docs of BufferedWriter.write:

    Ordinarily this method stores characters from the given array into this stream's buffer, flushing the buffer to the underlying stream as needed.

    (Emphasis mine.)

    The point of BufferedWriter is basically to consolidate lots of little writes into far fewer big writes, as that's usually more efficient (but more of a pain to code for). You shouldn't need to do anything special to get it to work properly though, other than making sure you flush it when you're finished with it - and calling close() will do this and flush/close the underlying writer anyway.

    In other words, relax - just write, write, write and close :) The only time you normally need to call flush manually is if you really, really need the data to be on disk now. (For instance, if you have a perpetual logger, you might want to flush it every so often so that whoever's reading the logs doesn't need to wait until the buffer's full before they can see new log entries!)

    0 讨论(0)
  • 2020-12-05 04:53

    If you have a loop alternating init and printAfterInfo, my guess about your problem is that you don't close your writer before creating a new one on the same file. You'd better create the BufferedWriter once and close it at the end of all the processing.

    0 讨论(0)
提交回复
热议问题