Java 程序中启动及关闭命令行程序

来源:互联网 发布:winebottler for mac 编辑:程序博客网 时间:2024/06/06 00:07


Java 程序中启动及关闭命令行程序

我需要在java中启动一个用C++编写的命令行程序.。用 Runtime.getRuntime().exec("c://example.exe"); 没有成功。

后来找到启动命令行程序的方法


Process process = Runtime.getRuntime().exec("cmd.exe /c start c://example.exe");

可是发现调用 process.destroy() 方法并无法结束用上述方法启动的程序。请问这是怎么原因?

我自己找到了一种方法结束它。在windows中,调用 tasklist 命令找到该程序的 pid 然后调用 taskkill 方法结束进程。


String programName = "example.exe";

Process process = Runtime.getRuntime().exec("cmd.exe /c start c://" + programName);


Thread.sleep(2000);


Process listprocess = Runtime.getRuntime().exec("cmd.exe /c tasklist");

InputStream is = listprocess.getInputStream();

byte[] buf = new byte[256];

BufferedReader r = new BufferedReader(new InputStreamReader(is));


StringBuffer sb = new StringBuffer();

String str = null;

while ((str = r.readLine()) != null) {

String id = null;

Matcher matcher = Pattern.compile(programName + "[ ]*([0-9]*)").matcher(str);

while (matcher.find()) {

if (matcher.groupCount() >= 1) {

id = matcher.group(1);

if (id != null) {

Integer pid = null;

try {

pid = Integer.parseInt(id);

} catch (NumberFormatException e) {

e.printStackTrace();

}

if (pid != null) {

Runtime.getRuntime().exec("cmd.exe /c taskkill /f /pid " + pid);

System.out.println("kill progress");

}

}

}

}

}

原创粉丝点击