java判断一个程序是否启动_Java判断应用程序启动状态并打开或关闭应用程序
时间: 2023-07-30 17:11:39 浏览: 74
要判断一个程序是否已经启动,可以使用Java中的`java.lang.management`包中的`RuntimeMXBean`类。
以下是一个示例代码,它可以检测一个名为"notepad.exe"的程序是否在Windows上启动,并打开或关闭该程序:
```java
import java.io.IOException;
import java.lang.management.ManagementFactory;
public class ProgramChecker {
public static void main(String[] args) {
String processName = "notepad.exe";
if (isProcessRunning(processName)) {
System.out.println(processName + " is running.");
closeProcess(processName);
} else {
System.out.println(processName + " is not running.");
openProcess(processName);
}
}
private static boolean isProcessRunning(String processName) {
try {
// Get the list of running processes
Process process = Runtime.getRuntime().exec("tasklist");
java.util.Scanner scanner = new java.util.Scanner(process.getInputStream());
while (scanner.hasNextLine()) {
String line = scanner.nextLine();
if (line.contains(processName)) {
return true;
}
}
scanner.close();
} catch (IOException e) {
e.printStackTrace();
}
return false;
}
private static void openProcess(String processName) {
try {
// Open the process
Runtime.getRuntime().exec(processName);
} catch (IOException e) {
e.printStackTrace();
}
}
private static void closeProcess(String processName) {
try {
// Get the PID of the process
String pid = ManagementFactory.getRuntimeMXBean().getName().split("@")[0];
// Kill the process
Runtime.getRuntime().exec("taskkill /F /PID " + pid);
} catch (IOException e) {
e.printStackTrace();
}
}
}
```
该代码使用`tasklist`命令获取当前正在运行的进程列表,并检查是否有一个名为"notepad.exe"的进程。如果进程正在运行,则使用`taskkill`命令关闭该进程。如果进程没有运行,则使用`Runtime.getRuntime().exec()`方法打开该进程。注意,这个示例代码只能在Windows上运行。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)