Java StreamTokenizer class

Introduction

StreamTokenizer populates three fields: ttype, sval, and nval during tokenize operation.

The ttype field tracks the token type.

The following are the four possible values for the ttype field:

Value Description
TT_EOF End of the stream reached.
TT_EOL End of line reached.
TT_WORDA string has been read as a token.
TT_NUMBER A number has been read as a token.

If the ttype has TT_WORD, the string value is stored in its field sval.

If it returns TT_NUBMER, its number value is stored in nval field.


import java.io.IOException;
import java.io.StreamTokenizer;
import java.io.StringReader;

public class Main {
  public static void main(String[] args) throws Exception {
    String str = "abc demo demo2s.com 123 321";
    StringReader sr = new StringReader(str);
    StreamTokenizer st = new StreamTokenizer(sr);

    try {// ww w.j  a  v a 2  s.c o m
      while (st.nextToken() != StreamTokenizer.TT_EOF) {
        switch (st.ttype) {
        case StreamTokenizer.TT_WORD: /* a word has been read */
          System.out.println("String value: " + st.sval);
          break;
        case StreamTokenizer.TT_NUMBER: /* a number has been read */
          System.out.println("Number value: " + st.nval);
          break;
        }
      }
    } catch (IOException e) {
      e.printStackTrace();
    }
  }
}



PreviousNext

Related