FileWriter和BufferedWriter之间的Java差异 [英] Java difference between FileWriter and BufferedWriter
问题描述
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();
我理解缓冲数据的概念,这是否意味着第一个例子将字符写入通过一个和第二个第一缓冲它的内存,并写入一次?
感谢您的帮助
在您的示例中,只有一个写入,所以BufferedWriter只是增加开销,你不需要。 所以这意味着第一个例子写字符一个接一个,第二个第一个将其缓存到内存并写入一次 在这两种情况下,字符串都是一次性写入的。 如果你只使用FileWriter,那么你的write(String)调用是这样的:public void write(String str ,int off,int len) 这使得一次系统调用,每次调用write(String) b> 其中BufferedWriter提高了效率, (int i = 0; i <100; i ++){ 如果没有BufferedWriter,可能会产生200(2 * 100)个系统调用并写入磁盘, 。使用BufferedWriter,这些可以全部缓冲在一起,因为默认的缓冲区大小是8192个字符,这成为只有1个系统调用来写入。 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 didnt copy the try-catch block here) and 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? thanks for the help BufferedWriter is more efficient if you In your example, you have only one write, so the BufferedWriter just add overhead you don't need. 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 In both cases, the string is written at once. If you use just FileWriter your write(String) calls This makes one system call, per call to write(String). Where BufferedWriter improves efficiency is in multiple small writes. 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差异的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
$ b
//一些代码
str.getChars(off,(off + len),cbuf,0);
write(cbuf,0,len);
$ b
writer.write(foorbar);
writer.write(NEW_LINE);
}
writer.close();
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();
public void write(String str, int off, int len)
// some code
str.getChars(off, (off + len), cbuf, 0);
write(cbuf, 0, len);
}
for(int i = 0; i < 100; i++) {
writer.write("foorbar");
writer.write(NEW_LINE);
}
writer.close();