我正在使用 FileWriter,我注意到了奇怪的行为。
我自己缓冲我的 Collection 和我使用的每 x 行
IOUtils.writelines(myList,"\n", writer );
它不写入文件。我继续用更多行调用它,只有在它非常满时才会写入文件。
它使用缓冲区吗?我在它的文档中找不到它。
最佳答案
the FileWriter
class overview的第二句说:
The constructors of this class assume that the default character encoding and the default byte-buffer size are acceptable. To specify these values yourself, construct an OutputStreamWriter on a FileOutputStream.
(我的重点)
很明显它被缓冲了(除非默认的字节缓冲区大小为零并且他们的措辞真的很奇怪)。
我怀疑它只是在 FileOutputStream
上使用了 OutputStreamWriter
。查看 OutputStreamWriter
:
Each invocation of a write() method causes the encoding converter to be invoked on the given character(s). The resulting bytes are accumulated in a buffer before being written to the underlying output stream.
(我的重点)
如果要确保各个级别的各种缓冲区都被刷新,请尽可能使用 flush
method .
关于java - FileWriter 是否使用缓冲区? (它的行为就像我的例子一样),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6108043/