mathphreak mathphreak - 7 months ago 17
Java Question

How to see if a Reader is at EOF?

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?

Answer

A 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();
Comments