End of File on a Java BufferedReader
Archive - Originally posted on "The Horse's Mouth" - 2007-06-22 06:56:08 - Graham EllisHow do you sense if a BufferedReader in Java has reached the end of file? Like so many "things Java" it's easy enough to do ... once you find that vital method in the lists of thousands of calls!
There's no "eof"; there's no checking the input to see if you got nothing back after a read as that happens when at the end of file AND at embedded blank lines. But the ready method tells you if you have data available of not - and that's the one to use.
Here's a sample piece of code in Java to echo the first 12 lines of a file, and to count all the lines in the file too.
File myFile = new File ("access_log.xyz");
BufferedReader newFile = new BufferedReader(new FileReader(myFile));
int k=1;
while (true){
if (! newFile.ready()) break;
String next_line = newFile.readLine();
if (k<12){
System.out.println("Line Number:"+k+" - "+next_line);
}
k++;
}