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!
The function feof() is used to check the end of file after EOF.
feof() — Test end of file (EOF) indicator.
The End of the File (EOF) indicates the end of input. After we enter the text, if we press ctrl+Z, the text terminates i.e. it indicates the file reached end nothing to read.
You can check using hasNextLine()
:
Scanner input = new Scanner(new File("\""+filename+"\""));
while(input.hasNextLine())
{
String data = input.nextLine();
}
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 thisScanner
has another token in its input. This method may block while waiting for input to scan. TheScanner
does not advance past any input.Specified by:
hasNext
in interfaceIterator<String>
Returns:
true
if and only if thisScanner
has another tokenThrows:
IllegalStateException
- if thisScanner
is closedSee Also:
Iterator
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With