如何从Java中查找并杀死正在运行的Win-Processes?

2022-09-01 12:37:25

我需要一种Java方法来找到一个正在运行的Win进程,从中我知道可执行文件的名称。我想看看它现在是否正在运行,如果我找到它,我需要一种方法来杀死该进程。


答案 1
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);
 }
}

答案 2

您可以使用命令行窗口工具,并使用 从 Java 调用它们。tasklisttaskkillRuntime.exec()


推荐