BufferedReader in Scanner's constructor

情到浓时终转凉″ 提交于 2019-12-13 05:07:03

问题


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.........

回答1:


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.

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



来源:https://stackoverflow.com/questions/19744943/bufferedreader-in-scanners-constructor

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!