Java Kill Process killProcess(String processName)

Here you can find the source of killProcess(String processName)

Description

Kills the Windows process name

License

Apache License

Parameter

Parameter Description
processName The process to kill

Return

True if it was successful, false otherwise

Declaration

static boolean killProcess(String processName) throws Exception 

Method Source Code


//package com.java2s;
//License from project: Apache License 

import java.io.IOException;
import java.io.InputStream;
import java.util.Scanner;

public class Main {
    /**//www.  j  a  v  a  2 s.  c o m
     * Kills the Windows process name
     *
     * @param processName The process to kill
     * @return True if it was successful, false otherwise
     */
    static boolean killProcess(String processName) throws Exception {
        if (isProcessRunning(processName)) {
            ProcessBuilder processBuilder = new ProcessBuilder();
            processBuilder.command("taskkill", "/F", "/IM", processName);
            Process process = processBuilder.start();
            process.waitFor();

            return !isProcessRunning(processName);
        }

        return false;
    }

    public static boolean isProcessRunning(String processName) throws IOException {
        ProcessBuilder processBuilder = new ProcessBuilder("tasklist");
        Process process = processBuilder.start();
        String tasksList = toString(process.getInputStream());

        return tasksList.contains(processName);
    }

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

Related

  1. killProcess(int port)
  2. killProcess(String name)
  3. killProcess(String processName)
  4. killProcessesTree(String rootNamePart)
  5. killProcessNix(String pid)
  6. killProcessWithArgs(List args)