0

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.........
notArefill
  • 786
  • 1
  • 11
  • 27

1 Answers1

2

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.

Martijn Courteaux
  • 67,591
  • 47
  • 198
  • 287
  • Plus one for mentioning that this is loaded into RAM. I suppose this implies that the BufferedReader doesn't have any benefit if the file is already in RAM. I.E. a file is uploaded by a user to a webpage, and you would like to parse this file before saving it to disk. Is this correct? – TigerBear Jun 09 '15 at 17:57
  • Just wanted to say that it actually isn't any faster, which is easily verifiable by comparing Scanner, Scanner with BufferedReader, and just BufferedReader. The 2 with Scanners are equally fast, the one with just BufferedReader is about 4x faster. – i'm a girl Dec 06 '20 at 17:54