从 STDIN 读取命令并在输入时执行每个命令
我想调整下面的代码以使用 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 + "`");
}
}
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 command `" + line + "`");
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
如果使用 JDK1.6,我们可以按如下方式执行主循环:
If using JDK1.6 we can do the main loop as the following: