Search code examples
while-loopbufferedreaderreadline

BufferedReader readLine used in while loop


I have seen BufferedReader using while loops to iterate through the contents of a file, with code more or less like:

try {
   FileReader fr = new FileReader(file);
   Buffered Reader br = new BufferedReader(fr);
   String line;

   while ( (line = br.readLine()) != null ) {
      // do something
   } 
} catch () {}

what I don't understand is how the while loop is internally incrementing its counter until it has read all lines in the document. To me, the while loop above means "if the first line (line[0]) is not null, do something (presumably an infinite number of times)", and never advancing past the first line of the document. What am I not understanding about BufferedReader or the .readLine() method?


Solution

  • I hope I get your question right. You would like to know how BufferedReader determines where to continue reading within the loop without a counting variable?

    If you take a look inside BufferedReader.class you will see a private int pos; counter that is incremented every time a char is read from the stream, e.g. in public int read(). Same is happening in readLine() with the difference that pos is incremented until the end of the line is reached.

    You can reset the internal counter using reset() function (this is to the last mark location, see here for details).