Run external program from Java, read output, allow interruption

前端 未结 5 1125
孤独总比滥情好
孤独总比滥情好 2020-11-29 08:18

I want to launch a process from Java, read its output, and get its return code. But while it\'s executing, I want to be able to cancel it. I start out by launching the proce

5条回答
  •  一生所求
    2020-11-29 09:20

    A helper class like this would do the trick:

    public class ProcessWatcher implements Runnable {
    
        private Process p;
        private volatile boolean finished = false;
    
        public ProcessWatcher(Process p) {
            this.p = p;
            new Thread(this).start();
        }
    
        public boolean isFinished() {
            return finished;
        }
    
        public void run() {
            try {
                p.waitFor();
            } catch (Exception e) {}
            finished = true;
        }
    
    }
    

    You would then implement your loop exactly as you describe:

    Process p = Runtime.getRuntime().exec("whatever command");
    ProcessWatcher pw = new ProcessWatcher(p);
    InputStream output = p.getInputStream();
    while(!pw.isFinished()) {
        processOutput(output);
        if(shouldCancel()) p.destroy();
        Thread.sleep(500);
    }
    

    Depending upon what conditions would make you want to destroy the process, you might want to do that in a separate thread. Otherwise, you may block while waiting for more program output to process and never really get the option to destroy it.

    EDIT: McDowell is 100% right in his comment below, so I've made the finished variable volatile.

提交回复
热议问题