20

I am trying to read text from a text file. I need help figuring out when the end of file has occured. How can I determine this in Java?

FileInputStream istream = new FileInputStream("\""+filename+"\"");      
Scanner input = new Scanner(istream);
while(EOF != true)
{
 ....
}

Thanks!

Blackbinary
  • 3,674
  • 15
  • 45
  • 61

2 Answers2

26

You can check using hasNextLine():

Scanner input = new Scanner(new File("\""+filename+"\""));
while(input.hasNextLine())
{
   String data = input.nextLine();
}
jjnguy
  • 128,890
  • 51
  • 289
  • 321
  • 5
    `Scanner.hasNextLLine()` will crash and burn if you're not reading an entire line at a time (`.nextLine()`). Otherwise, per Thomas Langston, use `.hasNext()` instead. – paulsm4 Nov 28 '16 at 07:02
6

Line based retrieval may be what you want, but token based can also be useful. You can see in documentation of Scanner

public boolean hasNext()

Returns true if this Scanner has another token in its input. This method may block while waiting for input to scan. The Scanner does not advance past any input.

Specified by: hasNext in interface Iterator<String>

Returns: true if and only if this Scanner has another token

Throws: IllegalStateException - if this Scanner is closed

See Also: Iterator

Ramesh-X
  • 3,854
  • 6
  • 40
  • 57
Thomas Langston
  • 3,688
  • 1
  • 22
  • 36