This week's book giveaway is in the Design forum.
We're giving away four copies of Design for the Mind and have Victor S. Yocco on-line!
See this thread for details.
Win a copy of Design for the Mind this week in the Design forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Problem with scanner

 
prashant casfdasfsatg
Greenhorn
Posts: 4
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
 
Winston Gutkowski
Bartender
Pie
Posts: 10226
58
Eclipse IDE Hibernate Ubuntu
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
 
Pat Farrell
Rancher
Posts: 4678
7
Linux Mac OS X VI Editor
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I haven't use Scanner this century. IMHO, it should be deprecated. Use BufferedReader as @winston suggests and all will be fine.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic