Search code examples
javaexecutionlive

How to get an live output from runtime execution in java?


Here is my code:

    Runtime runtime = Runtime.getRuntime();
    Process process = runtime.exec("cmd.exe /c kotlinc -script " + script.getAbsolutePath());
    process.waitFor();
    BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(process.getInputStream()));
    String line = "";
    while ((line = bufferedReader.readLine()) != null){
        System.out.println(line);
    }

All I want to have is an live output from the running script. Have somebody an idea how to do that?


Solution

  • Your process.waitFor() call is a blocking call, and only unblocks when the process ends, preventing your streams from working, since the streams will be closed when the process has ended.

    Read from the stream in a separate thread that you call the .waitFor() in, or read from the stream before calling .waitFor()

    Runtime runtime = Runtime.getRuntime();
    Process process = runtime.exec("cmd.exe /c kotlinc -script " + script.getAbsolutePath());
    BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(process.getInputStream()));
    String line = "";
    while ((line = bufferedReader.readLine()) != null){
        System.out.println(line);
    }
    int exitValue = process.waitFor();
    

    Incidentally, I would use a ProcessBuilder to get the Process, and not Runtime.getRuntime()