0

My input file:

/home/gcj/finals

I want to have each character after / My approach:

StringTokenizer sr = new StringTokenizer(br.readLine());
      String s = sr.nextToken("/");
                 while(s != null){
                     System.out.println(s);
                     s = sr.nextToken("/");
                 }

Output:

gcj
finals
Exception in thread "main" java.util.NoSuchElementException
    at java.util.StringTokenizer.nextToken(Unknown Source)
    at java.util.StringTokenizer.nextToken(Unknown Source)
    at jobs.TestClass.main(TestClass.java:118)

Please Help me out. OR if there any better method.

user4084025
  • 17
  • 1
  • 7

4 Answers4

1

Instead of while (s != null), use hasMoreTokens().

reservoirman
  • 119
  • 1
  • 11
0

As the StringTokenizer docs explains, you must use the hasMoreTokens method to loop instead of comparing next() to null.

 StringTokenizer st = new StringTokenizer(...);
 while (st.hasMoreTokens()) {
     System.out.println(st.nextToken());
 }

And again, as the docs explains, split is a better option to split a String in general.

Finally, since you're trying to read a file line by line, you should check out libraries like Apache Commons, they have what you're looking for in FileUtils.lineIterator.

phtrivier
  • 13,047
  • 6
  • 48
  • 79
0
for (String s : "/home/gcj/finals".split("/")) {
   System.out.println(s);
}
NPE
  • 486,780
  • 108
  • 951
  • 1,012
0

If you want to read a file, you can take the classes IO, In and Out from here. Then you can simply invoke IO.in.readFile(String filename).

Hope it helps.

Clemencio Morales Lucas.

Community
  • 1
  • 1