本文介绍了Scanner的构造函数中的BufferedReader的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在研究BufferedReader,Scanner和InputStreamReader类及其差异,并且我了解每个类的目的。我想要一个解释来澄清一件事:在Scanner的构造函数中传递BufferedReader的目的是什么?这样做的具体原因是什么?
下面是我要引用的示例。

I am studying the BufferedReader,Scanner and InputStreamReader classes and their differences and i understand the purpose of each one. I want an explanation to clarify one thing : what is the purpose of passing the BufferedReader in the Scanner's constructor? What is the specific reason for doing that?Below is the example i am referring to.

    Scanner s = null;
    try {
        s = new Scanner(new BufferedReader(new FileReader("file....")));
          //more code here.........


推荐答案

BufferedReader将创建一个缓冲区。这应该导致更快地读取文件。为什么?因为缓冲区中充满了文件的内容。因此,您将文件的较大块放在RAM中(如果要处理小文件,则缓冲区可以包含整个文件)。现在,如果扫描程序要读取两个字节,它可以从缓冲区读取两个字节,而不必向硬盘驱动器索要两个字节。

A BufferedReader will create a buffer. This should result in faster reading from the file. Why? Because the buffer gets filled with the contents of the file. So, you put a bigger chunk of the file in RAM (if you are dealing with small files, the buffer can contain the whole file). Now if the Scanner wants to read two bytes, it can read two bytes from the buffer, instead of having to ask for two bytes to the hard drive.

通常,读取10倍4096字节而不是4096倍10字节要快得多。

Generally speaking, it is much faster to read 10 times 4096 bytes instead of 4096 times 10 bytes.

这篇关于Scanner的构造函数中的BufferedReader的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-29 20:39