如何从控制台获取exect输出

daolsyd0  于 2021-07-03  发布在  Java
关注(0)|答案(1)|浏览(350)

当我启动命令时,我想从控制台得到确切的输出。这是我的密码:

Runtime runtime = Runtime.getRuntime();
Process p = null;
try {
    p = runtime.exec("cmd.exe /c kotlinc -script " + script.getAbsolutePath());
    p.getOutputStream().close(); // close stdin of child

    InputStream processStdOutput = p.getInputStream();
    Reader r = new InputStreamReader(processStdOutput);
    BufferedReader br = new BufferedReader(r);
    String line;
    while ((line = br.readLine()) != null) {
        output.setText(output.getText() + line + "\n");
    }

    p.waitFor();
    int code = p.exitValue();
    exitCode.setText("Exit Code: " + Integer.toString(code));

}
catch (InterruptedException e) {
    e.printStackTrace();
}
catch (IOException e){
    e.printStackTrace();
}
finally{
    if (p != null)
        p.destroy();
}

如果脚本没有任何错误,它只显示输出:例如,如果我只是在脚本中println(“test”),则输出为“test”。但是如果我有这样的东西:dasjhdaiushdkjashduisah,输出是空的,但是如果我从cmd启动脚本,输出将是:error: unresolved reference: dasjhdaiushdkjashduisah(script.kts:1:1) script.kts:1:1: error: unresolved reference: dasjhdaiushdkjashduisah 那么我应该如何获得exect输出呢?

4dc9hkyq

4dc9hkyq1#

它可以通过使用 p.getInputStream() 对于非错误输出和 p.getErrorStream() 对于有错误的输出

相关问题