How to detect EOF in Java?

It keeps running because it hasn’t encountered EOF. At end of stream:

  1. read() returns -1.
  2. read(byte[]) returns -1.
  3. read(byte[], int, int) returns -1.
  4. readLine() returns null.
  5. readXXX() for any other X throws EOFException.
  6. Scanner.hasNextXXX() returns false for any X.
  7. Scanner.nextXXX() throws NoSuchElementException for any X.

Unless you’ve encountered one of these, your program hasn’t encountered end of stream. NB \u001a is a Ctrl/z. Not EOF. EOF is not a character value.

Leave a Comment