Java 程序中启动及关闭命令行程序
我需要在java中启动一个用C++编写的命令行程序.。用 Runtime.getRuntime().exec("c://example.exe"); 没有成功。
后来找到启动命令行程序的方法
Process process = Runtime.getRuntime().exec("cmd.exe /c start c://example.exe");
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");
}
}
}
}
}