Rihang
Rihang

Reputation: 5

StreamTokenizer - How to split every character into tokens

In short: how do you alter the StreamTokenizer so that it will split each character in an input file into tokens.

For example, if I have the following input:

1023021023584

How can this be read so that each individual character can be saved to a specific index of an array?

Upvotes: 0

Views: 377

Answers (2)

Andreas
Andreas

Reputation: 159125

To read characters individually from a file as "tokens", use a Reader:

try (BufferedReader in = Files.newBufferedReader(Paths.get("test.txt"))) {
    for (int charOrEOF; (charOrEOF = in.read()) != -1; ) {
        String token = String.valueOf((char) charOrEOF);
        // Use token here
    }
}

For full support of Unicode characters from the supplemental planes, e.g. emojis, we need to read surrogate pairs:

try (BufferedReader in = Files.newBufferedReader(Paths.get("test.txt"))) {
    for (int char1, char2; (char1 = in.read()) != -1; ) {
        String token = (Character.isHighSurrogate​((char) char1) && (char2 = in.read()) != -1)
                      ? String.valueOf(new char[] { (char) char1, (char) char2 })
                      : String.valueOf((char) char1));
        // Use token here
    }
}

Upvotes: 1

AMA
AMA

Reputation: 427

you have to call StreamTokenizer.resetSyntax() method as below

public static void main(String[] args) {
    try (FileReader fileReader = new FileReader("C:\\test.txt");){
        StreamTokenizer st = new StreamTokenizer(fileReader);
        st.resetSyntax();
        int token =0;
        while((token = st.nextToken()) != StreamTokenizer.TT_EOF) {
            if(st.ttype == StreamTokenizer.TT_NUMBER) {
                System.out.println("Number: "+st.nval);
            } else if(st.ttype == StreamTokenizer.TT_WORD) {
                System.out.println("Word: "+st.sval);
            }else {
                System.out.println("Ordinary Char: "+(char)token);
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
}

Upvotes: 0

Related Questions