Reading lines with BufferedReader and checking the end of file

If there is 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 might be something I need to deal with, but if the code doesn’t just work.

If there is something there, everything is in order, but I can not guarantee that there will be something.

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 problem with something like this is that when I check the line for zero, it already moves to the next line, so how can I check it again?

I have not developed a way to do this - any suggestions would be a big help.

+7
java file-io readline bufferedreader
source share
4 answers

Am ... You can simply use this construct:

 String line; while ((line = r.readLine()) != null) { // do your stuff... } 
+24
source share

If you want a loop through all the lines to use this:

 while((line=br.readLine())!=null){ System.out.println(line); } br.close(); 
+2
source share

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

 public bool isEOF(BufferedReader br) { boolean result; try { result = br.ready(); } catch (IOException e) { System.err.println(e); } return result; } 
+1
source share

You could throw this error inside your loop. i.e:.

 String s = ""; while (true) { try { s = r.readline(); }catch(NullPointerException e) { r.close(); break; } //Do stuff with line } 

what everyone else should do should also work.

-2
source share

All Articles