• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Scanner class

 
Emanuel Campolo
Greenhorn
Posts: 3
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi everybody.. the following code creates scanner objects that read characters from a string and attempt to match the specified pattern.
Is there any way to read the whole file with the scanner object ? i mean, scan for the next subsequence that matches the pattern ? I want to avoid creating one scanner object per line readed.

 
Ankit Garg
Sheriff
Posts: 9528
33
Android Google Web Toolkit Hibernate IntelliJ IDE Java Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Emanuel! Welcome to javaranch.

Why don't you read the file completely first, then scan it. like this



I have not tested this code but I think it will work...
 
patrick avery
Ranch Hand
Posts: 46
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
If you use scanner.next(), it will read the whole file:

 
saipavan vallabhaneni
Ranch Hand
Posts: 34
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
hi Emanuel,
the following code might help you


a scanner can directly take file as an argument...and the scanner's findInLine() can take only a String...so specify the pattern you want in a String and pass it to findInLine() and check the result

 
Emanuel Campolo
Greenhorn
Posts: 3
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Yes ! It works great, thank you.. just a little comment.. I replaced the hasNext(Pattern p) method with the no-arg hasNext() method. That's because, i suppose, if in the first token the pattern is not matched, the expression returns false and it will never get into the loop.

PS:. Sorry for my english, i learned the language reading kathy sierra's certification book


Originally posted by Ankit Garg:
Hi Emanuel! Welcome to javaranch.

Why don't you read the file completely first, then scan it. like this



I have not tested this code but I think it will work...
 
Emanuel Campolo
Greenhorn
Posts: 3
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thank you saipavan vallabhaneni ! but with that code it doesn't even get into the loop.. I tried this and it runs but, while expression returns a false value when it is evaluated the first time.

Scanner s=new Scanner(texto)
while (s.findInLine(p) != null)
{
System.out.println(s.next());
}

Originally posted by saipavan vallabhaneni:
hi Emanuel,
the following code might help you


 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic