简体   繁体   中英

How to get an exect output from the console

When I start the command I would like to get the exact output from the console. This is my code:

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();
}

If the script doesnt have any errors it just displays the output: for example if I just println("test") in my script, the output is "test". But if I have something like that: dasjhdaiushdkjashduisah, the output is empty, but if I start the script from the cmd the output would be: error: unresolved reference: dasjhdaiushdkjashduisah(script.kts:1:1) script.kts:1:1: error: unresolved reference: dasjhdaiushdkjashduisah

So how should I get the exect output?

It can be solved by using the p.getInputStream() for the non error output and p.getErrorStream() for the output with errors

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM