Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why use BufferedReader in this case?

What is the difference between using a BufferedReader around the StringReader in the following code vs using the StringReader only? By loading up the DOM in line 2 of both examples, it seems like the BufferedReader is not necessary?

    InputSource is = new InputSource(new StringReader(html));
    Document dom = XMLResource.load(is).getDocument();

VS

    InputSource is = new InputSource(new BufferedReader(new StringReader(html)));
    Document dom = XMLResource.load(is).getDocument();
like image 814
Tony Eichelberger Avatar asked Jun 02 '09 19:06

Tony Eichelberger


People also ask

Why do we use BufferedReader?

BufferedReader is a Java class that reads text from the input stream. It buffers the characters so that it can get the efficient reading of characters, arrays, etc. It inherits the reader class and makes the code efficient since we can read the data line-by-line with the readline() method.

Why BufferedReader is faster than Scanner?

BufferedReader is a bit faster as compared to scanner because the scanner does the parsing of input data and BufferedReader simply reads a sequence of characters.

What is a BufferedReader in Java?

Java BufferedReader is a public Java class that reads text, using buffering to enable large reads at a time for efficiency, storing what is not needed immediately in memory for later use. Buffered readers are preferable for more demanding tasks, such as file and streamed readers.


1 Answers

In this particular case, I see no benefit. In general there are two benefits:

  • The oh-so-handy readLine() method is only defined in BufferedReader rather than Reader (irrelevant here)
  • BufferedReader reduces IO where individual calls to the underlying reader are potentially expensive (i.e. fewer chunky calls are faster than lots of little ones) - again, irrelevant for StringReader

Cut and paste fail?

like image 113
Jon Skeet Avatar answered Oct 15 '22 14:10

Jon Skeet