Error whilst using StringTokenizer on text file with multiple lines

前端 未结 4 1203
我在风中等你
我在风中等你 2021-01-07 11:11

I\'m trying to read a text file and split the words individually using string tokenizer utility in java.

The text file looks like this;

a 2000

4  
b         


        
4条回答
  •  走了就别回头了
    2021-01-07 11:52

    a) You always have to check StringTokenizer.hasMoreTokens() first. Throwing NoSuchElementException is the documented behaviour if no more tokens are available:

    token = new StringTokenizer (line);
    while(token.hasMoreTokens())
        words.add(token.nextToken());
    

    b) don't create a new Tokenizer for every line, unless your file is too large to fit into memory. Read the entire file to a String and let the tokenizer work on that

提交回复
热议问题