Java 中的缓冲区和文件
Buffer and File in Java
我是java的新手,我想问一下使用FileReader-FileWriter和使用BufferedReader-BufferedWriter有什么区别。除了速度还有其他理由使用 Buffered 吗?
在复制文件并将其内容粘贴到另一个文件的代码中,使用 BufferedReader 和 BufferedWriter 更好吗?
简短的版本是:文件 writer/reader 速度快但效率低下,但是缓冲的 writer/reader 可以节省 writes/reads 并以块的形式进行处理(基于缓冲区大小)效率更高但速度可能更慢(等待缓冲区填满)。
因此,为了回答您的问题,缓冲 writer/reader 通常是最好的,尤其是当您不确定要使用哪一个时。
看看 JavaDoc for the BufferedWriter,它很好地解释了它的工作原理:
In general, a Writer sends its output immediately to the underlying
character or byte stream. Unless prompt output is required, it is
advisable to wrap a BufferedWriter around any Writer whose write()
operations may be costly, such as FileWriters and OutputStreamWriters.
For example,
PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter("foo.out")));
will buffer the PrintWriter's output to the file. Without buffering,
each invocation of a print() method would cause characters to be
converted into bytes that would then be written immediately to the
file, which can be very inefficient.
我是java的新手,我想问一下使用FileReader-FileWriter和使用BufferedReader-BufferedWriter有什么区别。除了速度还有其他理由使用 Buffered 吗? 在复制文件并将其内容粘贴到另一个文件的代码中,使用 BufferedReader 和 BufferedWriter 更好吗?
简短的版本是:文件 writer/reader 速度快但效率低下,但是缓冲的 writer/reader 可以节省 writes/reads 并以块的形式进行处理(基于缓冲区大小)效率更高但速度可能更慢(等待缓冲区填满)。
因此,为了回答您的问题,缓冲 writer/reader 通常是最好的,尤其是当您不确定要使用哪一个时。
看看 JavaDoc for the BufferedWriter,它很好地解释了它的工作原理:
In general, a Writer sends its output immediately to the underlying character or byte stream. Unless prompt output is required, it is advisable to wrap a BufferedWriter around any Writer whose write() operations may be costly, such as FileWriters and OutputStreamWriters. For example,
PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter("foo.out")));
will buffer the PrintWriter's output to the file. Without buffering, each invocation of a print() method would cause characters to be converted into bytes that would then be written immediately to the file, which can be very inefficient.