Dưới đây là một mã đầy đủ để kiểm tra nếu một ứng dụng đang chạy trên một hệ thống Windows
hay không:
import java.awt.*;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.Scanner;
public class ApplicationUtilities
{
public static void runApplication(String applicationFilePath) throws IOException, InterruptedException
{
File application = new File(applicationFilePath);
String applicationName = application.getName();
if (!isProcessRunning(applicationName))
{
Desktop.getDesktop().open(application);
}
}
// http://stackoverflow.com/a/19005828/3764804
private static boolean isProcessRunning(String processName) throws IOException, InterruptedException
{
ProcessBuilder processBuilder = new ProcessBuilder("tasklist.exe");
Process process = processBuilder.start();
String tasksList = toString(process.getInputStream());
return tasksList.contains(processName);
}
// http://stackoverflow.com/a/5445161/3764804
private static String toString(InputStream inputStream)
{
Scanner scanner = new Scanner(inputStream, "UTF-8").useDelimiter("\\A");
String string = scanner.hasNext() ? scanner.next() : "";
scanner.close();
return string;
}
}
Ví dụ, bạn có thể sử dụng phương pháp runApplication()
để chỉ chạy các ứng dụng khi nó không hoạt động được nêu ra:
ApplicationUtilities.runApplication("C:\\Program Files (x86)\\WinSCP\\WinSCP.exe");
Nguyên tắc tương tự cũng áp dụng cho việc xóa tệp thi hành.
kiểm tra câu hỏi này: [Cách nhận danh sách các cửa sổ/quy trình mở hiện tại bằng Java?] (Http://stackoverflow.com/questions/54686/how-to-get-a-list-of-current- open-windows-process-with-java) – Renan
Các câu hỏi về tính toán chung là không có chủ đề trên Stack Overflow. Tôi đề nghị bạn thử vận may của mình trên [Siêu Người dùng] (http://superuser.com) –