Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to determine when end of file has been reached?

Tags:

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!

like image 314
Blackbinary Avatar asked Nov 17 '10 19:11

Blackbinary


People also ask

How can I tell if end of file is reached?

The function feof() is used to check the end of file after EOF.

Which of the following functions is used to determine if end of file has been reached while reading a file?

feof() — Test end of file (EOF) indicator.

How do you indicate end of file?

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.


2 Answers

You can check using hasNextLine():

Scanner input = new Scanner(new File("\""+filename+"\""));
while(input.hasNextLine())
{
   String data = input.nextLine();
}
like image 101
jjnguy Avatar answered Sep 22 '22 06:09

jjnguy


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

like image 23
Thomas Langston Avatar answered Sep 19 '22 06:09

Thomas Langston