---
title: "java 程序打开和关闭exe程序问题总结"
author: "xiaofeiyan"
date: "2014-05-22T12:13:41Z"
tags: []
categories: ["研发管理"]
slug: "java-exe"
draft: false
lastmod: "2014-05-22T12:13:40Z"
id: 2069873
url: "https://xiaofeiyan.iteye.com/blog/2069873"
---

花了两天的时间研究关于java程序打开一个外部的exe程序，关闭已经打开的exe进程的问题，总结如下：

场景：开发一个可视化窗口，两个按钮，启动，关闭。对两个按钮实现MouseListener接口，在鼠标按下按钮时执行操作。以下就是这两个按钮的功能。

启动：

Runtime.getRuntime().exec("E:/myClient/punchClient.exe");//启动.exe文件的方法

Runtime.getRuntime().exec("cmd.exe /c start c://example.exe");也是方法之一。

由于本功能只是启动一个项目，并没有其他操作，所以未声明Process 来接收返回值。似乎，打开一个exe文件变得很简单，至于Runtime的用法，以及exec方法的用法，可以百度下，不再多说。

关闭：

对于如何在一个java程序里关闭一个exe的进程，搜遍百度，归纳如下：

taskkill--window linux下用kill 执行该操作的用户必须有kill命令权限

对于taskkill 如果再cmd窗口执行该命令提示不是内部命令，而在windows\\system32中双击可以的话，那加入完整路径试试吧。

String command = "cmd.exe /c c:\\\\windows\\\\system32\\\\taskkill /f /im  punchClient.exe";

Process proc =Runtime.getRuntime().exec(command);

这里taskkill的参数意思就不介绍了。

这种方式在我的java环境里运行失败。接下来试试下面这种：

 Runtime.getRuntime().exec("tskill punchClient"); 测试成功

注意这里是tskill 进程名称不带.exe，带了就不行的哦。

tskill PID/ProcessName

既然这样，查找进程列表，取其PID ，试试

Runtime.getRuntime().exec("tskill 5036"); 也成功，

 

还有一种方法：

Runtime.getRuntime().exec("cmd.exe /c c:\\\\windows\\\\system32\\\\taskkill /f /pid  5036");测试成功

由于我的path的问题，这里必须是完整路径。

 

另外：获取PID的方法  关键代码如下

 

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() &gt;= 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");   

 }  

 }  

}