java - FileWriter是否使用缓冲区? (它的行为就像我的例子中那样) [英] java - Does FileWriter use a buffer? (it acts like it does in my example)

查看:706
本文介绍了java - FileWriter是否使用缓冲区? (它的行为就像我的例子中那样)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



我正在使用FileWriter,我注意到了奇怪的行为。
我自己缓冲我的收藏和我使用的每一行x


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.

推荐答案

FileWriter 类概述说:


此类的构造函数假定默认字符编码和默认字节缓冲区大小是可接受的。要自己指定这些值,请在FileOutputStream上构造一个OutputStreamWriter。

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.

(我的重点)

所以很明显它是缓冲的(除非默认字节缓冲区大小为零,并且它们的措辞真的很奇怪)。

So clearly it's buffered (unless the default byte-buffer size is zero and they're being really odd with their phrasing).

我怀疑它只是在 FileOutputStream 上使用 OutputStreamWriter 。查看 OutputStreamWriter

I suspect it's just using an OutputStreamWriter on a FileOutputStream. Looking at OutputStreamWriter:


每次调用write()方法都会导致编码要在给定字符上调用转换器。 结果字节在写入基础输出流之前累积在缓冲区中。

(我的重点)

如果你想确保刷新各种级别的各种缓冲区,请尽可能使用 flush 方法

If you want to ensure that various buffers at various levels are flushed, to the extent you can, look at using the flush method.

这篇关于java - FileWriter是否使用缓冲区? (它的行为就像我的例子中那样)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆