如何在java中检查使用Desktop执行的进程的状态

时间:2017-09-10 09:18:07

标签: java

我正在制作一个启动第三方应用程序的Java程序

Desktop dsktp=Desktop.getDesktop();
dsktp.open(new File("C:\\abcd.exe"));

它正在成功启动程序。 现在我只想在此过程完成(或关闭或强制终止)时启用下一个按钮。 如果此过程已结束,我如何获得状态?

2 个答案:

答案 0 :(得分:0)

因此,最好使用ProcessProcessBuilder

String[] args = {"C:\\abcd.exe"};
try {
    ProcessBuilder pb = new ProcessBuilder(args);
    pb = pb.redirectErrorStream(true);                // put error out with normal out

    Process p = pb.start();       
    BufferedReader br = new BufferedReader(new InputStreamReader(p.getInputStream()));

    String str; 
    while (( str= br.readLine()) != null) { 
        System.out.println(str);
    }
}catch (IOException e) {
    e.printStackTrace();
}

对于某些程序,您需要在开始后添加p.waitFor();,具体取决于它们的构建方式

答案 1 :(得分:0)

我会使用ProcessBuilder而是采用基于Interface的方法。这将是漫长的;但它应该有助于你理解应该解决这个问题的方式。

让我们先定义我们的界面 -

public interface ProcessEventListener {
    public void onComplete(Process process);
}

现在为了更好的模块化,我们创建一个ProcessManager类 -

public class ProcessManager extends Thread {
    private ProcessBuilder processBuilder;
    private Process process;
    private List<ProcessEventListener> processEventListeners = new ArrayList<ProcessEventListener>();

    public ProcessManager(String externalProcessPath, List<String> args) {
        args.add(0, externalProcessPath);
        processBuilder = new ProcessBuilder(args);
    }

    public ProcessManager(String externalProcessPath) {
        processBuilder = new ProcessBuilder(externalProcessPath);
    }

    public Process getProcess() {
        return process;
    }

    public void run() {
        try {
            process = processBuilder.start();
            // wait until the process is completed
            process.waitFor(); 
            // let the listeners know since the process is completed
            for (ProcessEventListener listener : processEventListeners) {
                listener.onComplete(process);
            }
        } catch (InterruptedException e) {}
    }

    public void addProcessEventListener(ProcessEventListener processEventListener) {
        processEventListeners.add(processEventListener);
    }

    public void removeAllListeners() {
        processEventListeners.clear();
    }
}

让我们定义一个实现接口的类 -

public class NextActionInitiator implements ProcessEventListener {
    public void onComplete(Process process) {
       // your workflow for next button action or enabling the button or
       // whatever; should go here.
    }
}

将所有这些结合在一起很简单。

// provide the process manager an absolute path of your executable; you 
// can also pass arguments as an ArrayList as second parameter.
// ...new ProcessManager("\absolute\path\of\your\exe", argList);
ProcessManager pManager = new ProcessManager("\absolute\path\of\your\exe");
NextActionInitiator nextActionInitiator = new NextActionInitiator();
pManager.addProcessEventListener(nextActionInitiator);
pManager.start();

onComplete中定义的NextActionInitiator方法只应在流程完成后触发。