我需要一种Java方法来查找正在运行的Win进程,我知道可执行文件的名称.我想看看它现在是否正在运行,如果我发现它,我需要一种方法来终止这个过程.
private static final String TASKLIST = "tasklist"; private static final String KILL = "taskkill /F /IM "; public static boolean isProcessRunning(String serviceName) throws Exception { Process p = Runtime.getRuntime().exec(TASKLIST); BufferedReader reader = new BufferedReader(new InputStreamReader( p.getInputStream())); String line; while ((line = reader.readLine()) != null) { System.out.println(line); if (line.contains(serviceName)) { return true; } } return false; } public static void killProcess(String serviceName) throws Exception { Runtime.getRuntime().exec(KILL + serviceName); }
例:
public static void main(String args[]) throws Exception { String processName = "WINWORD.EXE"; //System.out.print(isProcessRunning(processName)); if (isProcessRunning(processName)) { killProcess(processName); } }
您可以使用命令行窗口工具tasklist
,taskkill
并使用Java从Java调用它们Runtime.exec()
.