tags:

views:

44

answers:

3

My code needs to read in all of a file. Currently I'm using the following code:

BufferedReader r = new BufferedReader(new FileReader(myFile));
while (r.ready()) {
  String s = r.readLine();
  // do something with s
}
r.close();

If the file is currently empty, though, then s is null, which is no good. Is there any Reader that has an atEOF() method or equivalent?

+1  A: 

I have not used the ready() method. But it seems to be what you need. I wonder why it doesn't work for you?

Anyway, The (old-school) standard pattern for what you are trying to do is:

BufferedReader r = new BufferedReader(new FileReader(myFile));
String s = r.readLine();
while (s != null) {
    // do something with s
    s = r.readLine();
}
r.close();
Synesso
The ready() method only tells whether the next read will block. If the Reader is at eof the next call will not block; it will return immediately with an EOF indication (null for readline, -1 for read).
GregS
Even better: do-while instead of while.
Matt
A: 

the ready() method will not work. You must read from the stream and check the return value to see if you are at EOF.

GregS
A: 

check for null character.

Dheeraj Joshi