StreamTokenizer在遇到斜杠时停止

时间:2018-01-19 15:45:47

标签: java tokenize

考虑这个程序,可以在教程点上找到(其中br是一个BufferedReader对象):

boolean eof = false;
// Parse incoming request
StreamTokenizer st = new StreamTokenizer(br);
do {
    int token = st.nextToken();

    switch (token) {
        case StreamTokenizer.TT_EOF:
            System.out.println("End of File encountered.");
            eof = true;
            break;

        case StreamTokenizer.TT_EOL:
            System.out.println("End of Line encountered.");
            break;

        case StreamTokenizer.TT_WORD:
            System.out.println("Word: " + st.sval);
            break;

        case StreamTokenizer.TT_NUMBER:
            System.out.println("Number: " + st.nval);
            break;

        default:
            System.out.println((char) token + " encountered.");

            if (token == '!') {
                eof = true;
            }
    }
    } while (!eof);

此代码段适用于"Hello this is a string"之类的字符串,它会打印出来:

Word: Hello

Word: this

Word: is

Word: a

Word: string

但如果我这样做:"Hello /this is a string"它只会打印出来

Word: Hello

为什么会这样,我该如何解决?

1 个答案:

答案 0 :(得分:2)

正斜杠/不被视为StreamTokenizer类中的普通字符。您可以使用ordinaryChar方法更改该默认行为:

import java.io.*;

public class StreamTokenizerSO {
    public static void main(String[] args) throws IOException {
        String aString = "Hello /this is a string";
        Reader inputString = new StringReader(aString);
        BufferedReader br = new BufferedReader(inputString);

        boolean eof = false;
// Parse incoming request
        StreamTokenizer st = new StreamTokenizer(br);

        st.ordinaryChar('/');

        do {
            int token = st.nextToken();

            switch (token) {
                case StreamTokenizer.TT_EOF:
                    System.out.println("End of File encountered.");
                    eof = true;
                    break;

                case StreamTokenizer.TT_EOL:
                    System.out.println("End of Line encountered.");
                    break;

                case StreamTokenizer.TT_WORD:
                    System.out.println("Word: " + st.sval);
                    break;

                case StreamTokenizer.TT_NUMBER:
                    System.out.println("Number: " + st.nval);
                    break;

                default:
                    System.out.println((char) token + " encountered.");

                    if (token == '!') {
                        eof = true;
                    }
            }
        } while (!eof);
    }
}

通过Googling“StreamTokenizer正斜杠”找到了这个并获得了这个旧链接:http://www.dickbaldwin.com/java/Java061.htm