JAVA關閉exe程序問題總結

原文鏈接:https://www.iteye.com/blog/xiaofeiyan-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() >= 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");   

 }  

 }  

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章