Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to see if a Reader is at EOF?

Tags:

java

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?

like image 891
Melody Horn Avatar asked Sep 15 '10 01:09

Melody Horn


3 Answers

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.

like image 77
18446744073709551615 Avatar answered Nov 18 '22 09:11

18446744073709551615


Use this function:

public static boolean eof(Reader r) throws IOException {
    r.mark(1);
    int i = r.read();
    r.reset();
    return i < 0;
}
like image 42
KIM Taegyoon Avatar answered Nov 18 '22 09:11

KIM Taegyoon


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();
like image 1
Synesso Avatar answered Nov 18 '22 07:11

Synesso