This week's book giveaway is in the Servlets forum.
We're giving away four copies of Murach's Java Servlets and JSP and have Joel Murach on-line!
See this thread for details.
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


Win a copy of Murach's Java Servlets and JSP this week in the Servlets forum!
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: 7526
    
  18

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: 4646
    
    5

I haven't use Scanner this century. IMHO, it should be deprecated. Use BufferedReader as @winston suggests and all will be fine.
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Problem with scanner
 
Similar Threads
help compiling
Compilation error
Scanner Problems
Recently created folder is not coming in file.listFiles() method()
Multidimensional Array Help