我想调整下面的代码以使用ANTLRReaderStream
,这样我就不必为每一行创建一个新的解析器。但它需要单独处理每一行,我目前不知道该怎么做,而且我没有看到任何方法来询问解析器是否已准备好数据(或者与 String line = stdin.readLine() 等效的任何内容。
主循环:
stdin = new BufferedReader(new InputStreamReader(System.in));
while (true) {
String line = stdin.readLine();
if (line == null) {
System.exit(0);
}
processLine(line.trim());
}
处理单行:
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 command `" + line + "`");
}
}
最佳答案
如果使用JDK1.6,我们可以按如下方式执行主循环:
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!!");
}
关于java - 从 STDIN 读取命令并在输入时执行每个命令,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7559066/