check if some exe program is running on the windows

Solution 1:

You can run the following statement in your java program. Before that you need to know the name of the task in task manager. Say you want to see MS-Word is running. Then run MS-Word, go to task manager and under the process tab, you should see a process named word.exe. Figure out the name for the process you are targeting. Once you have that, you just run the following code:

String line;
String pidInfo ="";

Process p =Runtime.getRuntime().exec(System.getenv("windir") +"\\system32\\"+"tasklist.exe");

BufferedReader input =  new BufferedReader(new InputStreamReader(p.getInputStream()));

while ((line = input.readLine()) != null) {
    pidInfo+=line; 
}

input.close();

if(pidInfo.contains("your process name"))
{
    // do what you want
}

Solution 2:

Here's a full code for checking if an application is running on a Windows system or not:

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;
    }
}

For instance, you could use the runApplication() method to only run the application when it is not running yet:

ApplicationUtilities.runApplication("C:\\Program Files (x86)\\WinSCP\\WinSCP.exe");

The same principle applies for deleting the executable.

Solution 3:

You can try running the following code :

Runtime rt = Runtime.getRuntime();

and execute "tasklist"

tasklist returns a list of currently executing processes (as shown in the task manager's process tab).

Solution 4:

Just a suggestion for users of Java 9 or higher.
It's even operating system independent:

Interface ProcessHandle
static Stream<ProcessHandle>    allProcesses​()

More details at:
https://docs.oracle.com/javase/9/docs/api/java/lang/ProcessHandle.html