The project has a requirement to wake up the local desktop program through a web page hyperlink, and there is a small bug that repeatedly opens the desktop program. An interface needs to be opened in the background to determine whether the local desktop program is open. It can be achieved by the following simple method.
To detect whether a program is running under the specified local path, you can use the Java ProcessBuilder class to achieve. Here is a sample code:
Take todesk remote software as an example
import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
public class ProgramRunningCheck {
public static void main(String[] args) {
String programPath = "C:\Program Files (x86)\ToDesk\ToDesk.exe"; // 要检测的程序路径
if (isProgramRunning(programPath)) {
System.out.println(programPath + " is running.");
} else {
System.out.println(programPath + " is not running.");
}
}
public static boolean isProgramRunning(String programPath) {
boolean isRunning = false;
String os = System.getProperty("os.name").toLowerCase();
File programFile = new File(programPath);
String programName = programFile.getName();
try {
ProcessBuilder processBuilder;
if (os.contains("win")) {
// Windows系统
processBuilder = new ProcessBuilder("tasklist");
} else {
// 非Windows系统
processBuilder = new ProcessBuilder("ps", "-e");
}
Process process = processBuilder.start();
InputStream inputStream = process.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
String line;
while ((line = reader.readLine()) != null) {
if (line.contains(programName)) {
isRunning = true;
break;
}
}
reader.close();
inputStream.close();
process.destroy();
} catch (IOException e) {
e.printStackTrace();
}
return isRunning;
}
}
Test Results
Implementation logic description:
Use
ProcessBuilder
to execute an operating system command to get a list of running programs. In the Windows system, usetasklist
the command to obtain the program list; in the non-Windows system, useps -e
the command to obtain the program list.Then traverse the obtained program list to determine whether the program name to be detected is included, and if it is included, it means that the program is running.
Please modify
programPath
the value of the variable according to the actual situation so that it points to the program path to be detected.