flush in java.io.FileWriter

后端 未结 9 1128
清酒与你
清酒与你 2020-11-30 07:33

I have a question in my mind that, while writing into the file, before closing is done, should we include flush()??. If so what it will do exactly? dont streams auto flush??

相关标签:
9条回答
  • 2020-11-30 07:48

    Writers and streams usually buffer some of your output data in memory and try to write it in bigger blocks at a time. flushing will cause an immediate write to disk from the buffer, so if the program crashes that data won't be lost. Of course there's no guarantee, as the disk may not physically write the data immediately, so it could still be lost. But then it wouldn't be the Java program's fault :)

    PrintWriters auto-flush (by default) when you write an end-of-line, and of course streams and buffers flush when you close them. Other than that, there's flushing only when the buffer is full.

    0 讨论(0)
  • 2020-11-30 07:49

    I would highly recommend to call flush before close. Basically it writes remaining bufferized data into file.

    If you call flush explicitly you may be sure that any IOException coming out of close is really catastrophic and related to releasing system resources.

    When you flush yourself, you can handle its IOException in the same way as you handle your data write exceptions.

    0 讨论(0)
  • 2020-11-30 07:49

    Another usecase for flushing in program is writing progress of longrunning job into file (so it can be stopped and restarted later. You want to be sure that data is safe on the drive.

    while (true) {
      computeStuff();
      progresss += 1;
      out.write(String.format("%d", progress));
      out.flush();
    }
    out.close();
    
    0 讨论(0)
  • 2020-11-30 07:57

    There's no point in calling flush() just before a close(), as others have said. The time to use flush() is if you are keeping the file open but want to ensure that previous writes have been fully completed.

    0 讨论(0)
  • 2020-11-30 07:58

    Close automatically flushes. You don't need to call it.

    0 讨论(0)
  • 2020-11-30 08:04

    As said, you don't usually need to flush.

    It only makes sense if, for some reason, you want another process to see the complete contents of a file you're working with, without closing it. For example, it could be used for a file that is concurrently modified by multiple processes, although with a LOT of care :-)

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