Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reading lines with BufferedReader and checking for end of file

If I have something like this in my code:

String line = r.readLine();  //Where r is a bufferedReader

How can I avoid a crash if the next line is the end of the file? (i.e. null)

I need to read the next line because there may be something there that I need to deal with but if there isn't the code just crashes.

If there is something there then all is OK, but I can't be guaranteed that there will be something there.

So if I do something like: (pseudo code):

if (r.readLine is null)
//End code

else {check line again and excecute code depending on what the next line is}

The issue I have with something like this is, that when I check the line against null, it already moves onto the next line, so how can I check it again?

I've not worked out a way to do this - any suggestions would be a great help.

like image 730
Zippy Avatar asked Jul 16 '13 14:07

Zippy


3 Answers

Am... You can simply use such a construction:

String line;

while ((line = r.readLine()) != null) {
   // do your stuff...
}
like image 158
Andremoniy Avatar answered Nov 12 '22 12:11

Andremoniy


If you want loop through all lines use that:

while((line=br.readLine())!=null){
    System.out.println(line);
}
br.close();
like image 29
Lugaru Avatar answered Nov 12 '22 11:11

Lugaru


You can use the following to check for the end of file.

public bool isEOF(BufferedReader br)  
{
     boolean result;

     try 
     {
         result = br.ready();
     } 
     catch (IOException e)
     {
         System.err.println(e);
     }
     return result;
}
like image 5
Stephen Whitlock Avatar answered Nov 12 '22 10:11

Stephen Whitlock