听控制台命令输出

时间:2015-12-15 01:54:25

标签: java bufferedreader processbuilder

我想在我的Java应用程序中运行一个控制台命令,它在收到消息时会监听传入的消息并记录到控制台。当我在终端中执行它时,控制台命令运行正常。所以我想运行命令,然后在输出一行时执行某些操作,然后继续运行并侦听其他新消息。我通过以下代码尝试了这个:

try {
    ProcessBuilder builder = new ProcessBuilder(PYTHON_PATH, YOWSUP_CLI_PATH, "demos", "-r", "-c", YOWSUP_CONFIG);
    builder.redirectErrorStream(true);
    Process p = builder.start();
    BufferedReader reader = new BufferedReader(new InputStreamReader(p.getInputStream()));

    String line = "";
    log.info("Started listening...");

    // It does nothing from here on
    while ((line = reader.readLine()) != null) {
        log.info(line);
    }
    log.info("Stopped listening.");
} catch (Exception e) {
    e.printStackTrace();
}

但是当我运行这段代码时,它会记录“Started listening ...”字符串,所以我发送一条消息试一试,但它没有记录任何内容,只是继续运行而没有做任何事情。

如果我没有正确解释,只要这样说吧!

2 个答案:

答案 0 :(得分:0)

你可以使用这样的rt.exec命令:

try {               
            proc = rt.exec(command);
            BufferedReader stdInput = new BufferedReader(new InputStreamReader(proc.getInputStream()));
            BufferedReader stdError = new BufferedReader(new InputStreamReader(proc.getErrorStream()));
            int value=0;
            String line = null;
            while ((line = stdInput.readLine()) != null) {      
                System.out.println(line);
            }
            while ((line = stdError.readLine()) != null) {
                System.out.println(line);
            }
            proc.waitFor();
        } catch (Exception e) {
            // TODO: handle exception
            e.printStackTrace();
        }

答案 1 :(得分:0)

我使用" -u"我的命令中的参数,使用MadProgrammer中的this answer