user4084025
user4084025

Reputation: 17

Reading an input file in java

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.

Upvotes: 0

Views: 78

Answers (4)

phtrivier
phtrivier

Reputation: 13425

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.

Upvotes: 0

reservoirman
reservoirman

Reputation: 119

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

Upvotes: 1

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.

Upvotes: 0

NPE
NPE

Reputation: 500913

for (String s : "/home/gcj/finals".split("/")) {
   System.out.println(s);
}

Upvotes: 0

Related Questions