Does any one know how do I get the current open windows or process of a local machine using Java?
What I\'m trying to do is: list the current open task, windows or
This might be useful for apps with a bundled JRE: I scan for the folder name that i'm running the application from: so if you're application is executing from:
C:\Dev\build\SomeJavaApp\jre-9.0.1\bin\javaw.exe
then you can find if it's already running in J9, by:
public static void main(String[] args) {
AtomicBoolean isRunning = new AtomicBoolean(false);
ProcessHandle.allProcesses()
.filter(ph -> ph.info().command().isPresent() && ph.info().command().get().contains("SomeJavaApp"))
.forEach((process) -> {
isRunning.set(true);
});
if (isRunning.get()) System.out.println("SomeJavaApp is running already");
}
For windows I use following:
Process process = new ProcessBuilder("tasklist.exe", "/fo", "csv", "/nh").start();
new Thread(() -> {
Scanner sc = new Scanner(process.getInputStream());
if (sc.hasNextLine()) sc.nextLine();
while (sc.hasNextLine()) {
String line = sc.nextLine();
String[] parts = line.split(",");
String unq = parts[0].substring(1).replaceFirst(".$", "");
String pid = parts[1].substring(1).replaceFirst(".$", "");
System.out.println(unq + " " + pid);
}
}).start();
process.waitFor();
System.out.println("Done");