从Java中查找并杀死正在运行的Windows进程,可以通过以下几个步骤:
ProcessBuilder
和tasklist
命令查找进程ID(PID)taskkill
命令杀死进程以下是一个示例代码:
import java.io.BufferedReader;
import java.io.InputStreamReader;
public class KillWindowsProcess {
public static void main(String[] args) {
String processName = "notepad.exe"; // 要查找并杀死的进程名称
killProcess(processName);
}
public static void killProcess(String processName) {
try {
ProcessBuilder processBuilder = new ProcessBuilder("tasklist.exe");
Process process = processBuilder.start();
BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
String line;
while ((line = reader.readLine()) != null) {
if (line.contains(processName)) {
String[] parts = line.split("\\s+");
String pid = parts[1];
System.out.println("找到进程,PID: " + pid);
processBuilder = new ProcessBuilder("taskkill.exe", "/F", "/PID", pid);
processBuilder.start();
System.out.println("进程已杀死");
break;
}
}
reader.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
这段代码会查找名为notepad.exe
的进程,并杀死它。请注意,这个代码示例仅适用于Windows操作系统。
推荐的腾讯云相关产品:
产品介绍链接地址:
领取专属 10元无门槛券
手把手带您无忧上云