问题描述
它们之间有什么区别?我只是在学习 Java ATM,但似乎我可以双向写入文件,即(我没有在这里复制 try-catch 块.)
What's the difference between those? I'm just learning Java ATM, but it seems like I can write to a file both ways i.e. (I didn't copy the try-catch block here.)
FileWriter file = new FileWriter("foo.txt");
file.write("foobar");
file.close();
和
FileWriter file = new FileWriter("foo.txt");
BufferedWriter bf = new BufferedWriter(file);
bf.write("foobar");
bf.close();
我理解先缓冲数据的概念,那么是不是说第一个例子一个一个地写入字符,第二个第一个将它缓冲到内存并写入一次?
I understand the concept of buffering the data first, so does that mean the first example writes the characters one by one and the second first buffers it to the memory and writes it once?
推荐答案
BufferedWriter 效率更高
BufferedWriter is more efficient if you
- 在刷新/关闭之间有多次写入
- 与缓冲区大小相比,写入很小.
在您的示例中,您只有一次写入,因此 BufferedWriter 只会增加您不需要的开销.
In your example, you have only one write, so the BufferedWriter just add overhead you don't need.
这是否意味着第一个示例将字符一个一个地写入,第二个示例将其缓冲到内存中并写入一次
在这两种情况下,字符串都是一次性写入的.
In both cases, the string is written at once.
如果你只使用 FileWriter 你的 write(String) 调用
If you use just FileWriter your write(String) calls
public void write(String str, int off, int len)
// some code
str.getChars(off, (off + len), cbuf, 0);
write(cbuf, 0, len);
}
每次调用 write(String) 都会进行一次系统调用.
This makes one system call, per call to write(String).
BufferedWriter 提高效率的地方在于多次小写.
Where BufferedWriter improves efficiency is in multiple small writes.
for(int i = 0; i < 100; i++) {
writer.write("foorbar");
writer.write(NEW_LINE);
}
writer.close();
如果没有 BufferedWriter,这可能会进行 200 (2 * 100) 次系统调用并写入磁盘,这是低效的.使用 BufferedWriter,这些都可以一起缓冲,并且由于默认缓冲区大小为 8192 个字符,因此只需 1 个系统调用即可写入.
Without a BufferedWriter this could make 200 (2 * 100) system calls and writes to disk which is inefficient. With a BufferedWriter, these can all be buffered together and as the default buffer size is 8192 characters this become just 1 system call to write.
这篇关于FileWriter 和 BufferedWriter 之间的 Java 区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!