Java-StreamTokenizer

StreamTokenizer

The StreamTokenizer is used to breaks up the Reading stream into tokens that are delimited by sets of characters. The next token is obtained from the Reading stream by calling nextToken( ). It returns the type of token.

StreamTokenizer defines four int constants : TT EOF, TT EOL, TT NUMBER, and TT WORD. There are three instance variables : nval, sval, and ttype. The nval is a public double used to hold the values of numbers as they are recognized. The sval is a public string used to hold the value of any words as they are recognized. The ttype is a public int indicating the type of token that has just been read by the nextToken( ) method. If the token is a word, ttype equals TT WORD. If the token is a number, ttype equals TT NUMBER. If the token is a single character, ttype contains its value. If an end of line condition has been encountered, ttype equals TT EOL. If the end of the stream has been encountered, ttype equals TT EOF.

Program


Program Source

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

class Javaapp {
    
    public static void main(String[] args) throws IOException {
        
        String str = "Data1 50 Data2 100 Data3 150";
        StringReader sr = new StringReader(str);
        StreamTokenizer st = new StreamTokenizer(sr);

        while(st.nextToken() != StreamTokenizer.TT_EOF)
        {
            if(st.ttype==StreamTokenizer.TT_WORD)
            {
                System.out.println("Word : "+st.sval);
            }else if(st.ttype==StreamTokenizer.TT_NUMBER)
            {
                System.out.println("Number : "+(int)st.nval);
            }
        }
        sr.close();
    }
}

Leave a Comment