java - FileWriter 是否使用缓冲区? (它的行为就像我的示例中一样)
我正在使用 FileWriter,我注意到奇怪的行为。 我自己缓冲我的集合,并且我使用的每 x 行
IOUtils.writelines(myList,"\n", writer );
它不会写入文件。我继续用更多行调用它,只有在它非常满后才会写入文件。
它使用缓冲区吗?我在其文档中找不到它。
I am using FileWriter and I have noticed strange behavior.
I buffer my collection myself and every x rows I use
IOUtils.writelines(myList,"\n", writer );
It doesnt write to the file. I continue to call it with more lines and only after it is very full it writes to the file.
Does it use a buffer? I cant find it in its documentation.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
FileWriter
类概述的第二句 说:(我的重点)
很明显它是被缓冲的(除非默认的字节缓冲区大小为零并且他们的措辞非常奇怪)。
我怀疑它只是在
FileOutputStream
上使用OutputStreamWriter
。查看OutputStreamWriter:(我的重点)
如果要确保刷新各个级别的各个缓冲区,请执行以下操作:尽可能使用
刷新
方法。The second sentence of the
FileWriter
class overview says:(My emphasis)
So clearly it's buffered (unless the default byte-buffer size is zero and they're being really odd with their phrasing).
I suspect it's just using an
OutputStreamWriter
on aFileOutputStream
. Looking atOutputStreamWriter
:(My emphasis)
If you want to ensure that various buffers at various levels are flushed, to the extent you can, look at using the
flush
method.我怀疑这是一个实现细节,但我希望大多数实现都使用缓冲区,是的。您当然不应该依赖它是无缓冲的。当您刷新或关闭 writer 时,应该没问题。
请注意,我个人不喜欢使用
FileWriter
因为它不允许您指定字符编码 - 我通常会将FileOutputStream
包装在OutputStreamWriter
中反而。I suspect it's an implementation detail, but I would expect most implementations to use a buffer, yes. You certainly shouldn't rely on it being unbuffered. When you flush or close the writer, it should be fine.
Note that personally I dislike using
FileWriter
as it doesn't allow you to specify the character encoding - I would typically wrap aFileOutputStream
in anOutputStreamWriter
instead.似乎它使用缓冲区,但以其他方式(低级别,缓冲区默认情况下可能为空)。需要用BufferedWriter来包装它。来自 BufferedWriter javadoc:
Seems that it uses buffer but in some other way (low-level, buffer could be empty by default). Need to wrap it by BufferedWriter. From BufferedWriter javadoc:
查看
sun.nio.cs.StreamEncoder.CharsetSE.implWrite()
类。它使用ByteBuffer。
StreamEncoder.CharsetSE 类由 OutputStreamWriter 内部使用,而 OutputStreamWriter 又由 FileWriter 内部使用。
Look at the class
sun.nio.cs.StreamEncoder.CharsetSE.implWrite()
.It uses a ByteBuffer.
The class StreamEncoder.CharsetSE is internally used by OutputStreamWriter which inturn is internally used by FileWriter.