Search code examples
javabufferedreader

BufferedReader in Scanner's constructor


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

Solution

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