GeeCON Prague 2014*
The moose likes Java in General and the fly likes Problem with scanner Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


JavaRanch » Java Forums » Java » Java in General
Bookmark "Problem with scanner" Watch "Problem with scanner" New topic
Author

Problem with scanner

prashant casfdasfsatg
Greenhorn

Joined: Feb 09, 2013
Posts: 4
Hi i am using scanner for reading a file line by line but on reaching end of file it gives error instead of returning null;
but with buffered reader it does not gives error.
I am unable to understand problem
File fl=new File("/home/nl/infosysData2.csv");
Scanner sc=new Scanner(fl);
for(int i=0;;i++)
{
line=sc.nextLine();
if(line==null)
break;
}


*****output******
it reads all lines and after reading last line it gives following error
Exception in thread "main" java.util.NoSuchElementException

Thanks & Regards
Prashant C.
"Those who never made a mistake never made a discovery"
Winston Gutkowski
Bartender

Joined: Mar 17, 2011
Posts: 7892
    
  21

prashant casfdasfsatg wrote:Hi i am using scanner for reading a file line by line but on reaching end of file it gives error instead of returning null;
but with buffered reader it does not gives error.

That's because the two classes' nextLine() methods do not work the same way:
BufferedReader's is specifically documented to return null if no line is available, while Scanner's does exactly what you've seen.

Personally, I'm not a big fan of Scanner; but if you want to use it, you need to look at its hasNextLine() method.

Winston

Isn't it funny how there's always time and money enough to do it WRONG?
Articles by Winston can be found here
Pat Farrell
Rancher

Joined: Aug 11, 2007
Posts: 4659
    
    5

I haven't use Scanner this century. IMHO, it should be deprecated. Use BufferedReader as @winston suggests and all will be fine.
 
GeeCON Prague 2014
 
subject: Problem with scanner