java - FileWriter 是否使用缓冲区? (它的行为就像我的例子一样)

标签 java filewriter


我正在使用 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/

相关文章:

java - OptionalInt 和 int 之间的区别?

java - Ho 获取 HTTP 输入字段值并使用它来使用 c :if 进行一些测试

java - 开始看到对象堆异常 Java 6

Scala 在 while 循环内写入和读取文件

java - 在 Java 中创建具有不同名称的新文本文件

java - 从方法返回 double 值

java - 如何将 test 和 main 的属性注入(inject)到多模块 gradle spring boot 项目的每个子模块中?

java - 在java中用filewriter保存文件时如何设置目录?

Java - 使用 IO - 说明

java - 写入文件时遇到问题