How to see if a Reader is at EOF?

Melody Horn picture Melody Horn · Sep 15, 2010 · Viewed 31.7k times · Source

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

18446744073709551615 picture 18446744073709551615 · Feb 27, 2015

The docs say:

public int read() throws IOException
Returns: The character read, as an integer in the range 0 to 65535 (0x00-0xffff), or -1 if the end of the stream has been reached.

So in the case of a Reader one should check against EOF like

// Reader r = ...;
int c;
while (-1 != (c=r.read()) {
    // use c
}

In the case of a BufferedReader and readLine(), it may be

String s;
while (null != (s=br.readLine())) {
    // use s
}

because readLine() returns null on EOF.