开发者

Reading commands from STDIN and executing each as it is entered

I'd like to adapt the code below to use a ANTLRReaderStream so I don't have to create a new parser for each line. But it needs to process each line individually, which I don't have any idea how to do currently, and I don't see any way to ask the parser whether it has data ready (or whatever would be the equivalent of String line = stdin.readLine().

main loop:

stdin = new BufferedReader(new InputStreamReader(System.in));

while (true) {
    String line = stdin.readLine();
    if (line == null) {
        System.exit(0);
    }

    processLine(line.trim());
}

handle a single line:

public void processLine(String line) throws IOException {
    try {
        QuotaControlCommandsLexer lexer = new QuotaControlCommandsLexer();
        lexer.setCharStream(new ANTLRStringStream(line));           
        CommonTokenStream tokens = new CommonTokenStream(lexer);
        QuotaControlCommandsParser parser = new QuotaControlCommandsParser(tokens);

        Command cmd = parser.command();
        boolean result = cmd.execute();         
        output(result ? "1" : "0");
        stdout.flush();
    }
    catch (RecognitionException e) {
        logger.error("invalid command: " + line);
        output("ERROR: invalid c开发者_如何学Pythonommand `" + line + "`");
    }
}


If using JDK1.6 we can do the main loop as the following:

    Console console = System.console();

    if (console != null) {
        String line = null;

        while ((line = console.readLine()) != null) {
            processLine(line.trim());
        }
    } else {
        System.out.println("No console available!!");
    }
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜