java-啟動和關閉.exe程式
阿新 • • 發佈:2018-12-18
連結:
https://www.cnblogs.com/pengpengzhang/p/8675740.html
https://blog.csdn.net/ZHANGHUI3239619/article/details/78808129
例:
// 啟用exe客戶端 @RequestMapping("/startUpXFExe") @ResponseBody public ResponseResult startUpXFExe(ModelMap map, HttpServletRequest request) { ResponseResult responseResult= new ResponseResult(ResponseResult.FAILURECODE); String exePathXF = SysConfigItemValue.getValue("exePathXF");//exe存放路徑 if (StringUtils.isNotBlank(exePathXF)) { String procName = "iflytek.Court.Client.exe"; String result = checkProcess(procName);//檢查exe程序 if(result.isEmpty()) { try { //啟動exe執行程式 Desktop.getDesktop().open(new File(exePathXF)); responseResult.setCode(ResponseResult.SUCCESSCODE); //responseResult.setMsg("程式啟動成功。"); } catch (Exception e) { e.printStackTrace(); responseResult.setMsg("程式:" + exePathXF + "不存在!"); logger.error("程式:" + exePathXF + "不存在!"); } }else { responseResult.setMsg(result); } } return responseResult; } /** * 檢查程序是否存在,存在則殺死程序 * @param procName */ public String checkProcess(String procName) { String result = ""; //判斷是否存在程序 Boolean existProc = false; BufferedReader bufferedReader = null; try { Process proc = Runtime.getRuntime().exec("tasklist -fi " + '"' + "imagename eq " + procName +'"'); bufferedReader = new BufferedReader(new InputStreamReader(proc.getInputStream())); String line = null; while ((line = bufferedReader.readLine()) != null) { if (line.contains(procName)) { existProc = true;//存在 } } } catch (Exception ex) { result = "查詢程式程序異常:"+ex.getMessage(); logger.error("查詢程式程序異常:"+ex.getMessage()); return result; } finally { if (bufferedReader != null) { try { bufferedReader.close(); } catch (Exception ex) {} } } // 存在,則先殺死該程序 if (existProc) { BufferedReader br = null; try { if (StringUtils.isNotBlank(procName)) { //執行cmd命令 String command = "taskkill /F /IM " + procName; Runtime runtime = Runtime.getRuntime(); Process process = runtime.exec("cmd /c " + command); br = new BufferedReader(new InputStreamReader(process.getInputStream(), "UTF-8")); String line = null; StringBuilder build = new StringBuilder(); while ((line = br.readLine()) != null) { build.append(line); } } } catch (Exception e) { result = "關閉程式程序異常:"+e.getMessage(); logger.error("關閉程式程序異常:"+e.getMessage()); return result; } finally { if (br != null) { try { br.close(); } catch (Exception ex) {} } } } return result; }