TASKKILL command implementation using JAVA

左心房为你撑大大i 提交于 2019-12-13 02:53:45

问题


I have two methods written in JAVA, the taskkill() and taskkill(String strProcessName), given below:

    public static Timer taskkill() {

        TimerTask timerTask = new TimerTask() {

        @Override
        public void run() {             
            taskkill("notepad*");
        taskkill("matlab*");
        }
    };

    Timer timer = new Timer("MyTimer");  //create a new Timer

    timer.scheduleAtFixedRate(timerTask, 30, 10000);  //this line starts the timer at the same time its executed

    return timer;
}

public static void taskkill(String strProcessName) {
    String strCmdLine = null;
    strCmdLine = String.format("taskkill /FI \"WINDOWTITLE eq %s\" ", strProcessName);

    Runtime rt = Runtime.getRuntime();
    try {
        Process pr = rt.exec(strCmdLine);
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}

My question is, when the program runs it kills both notepad and matlab programs and the timer continues after every 3 seconds to kill these files if they run. Now I want to use ‘ne’ instead of ‘eq’ under taskkill(String strProcessName) and want to kill every program except notepad and matlab. But I failed to do so. Kindly help me in running the program.


回答1:


Here you are. You can use methods taskKill(String name) (kill one task with name 'name') and taskKillExcept(String... except) (kill all tasks except tasks in argument 'except').

I tested taskKill(String), but i didn't test taskKillExcept(String...), it can shutdown your pc.

/*** Class Run.java ***/
import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

public class Run {
    public static Timer taskKill() {

        TimerTask timerTask = new TimerTask() {

            @Override
            public void run() {             
                Run.taskKill("notepad*");
                Run.taskKill("matlab*");
            }
        };
        Timer timer = new Timer("MyTimer");  //create a new Timer
        timer.scheduleAtFixedRate(timerTask, 30, 10000);  //this line starts the timer at the same time its executed

        return timer;
    }


    /*** Task Tools ***/

    //Kill ONE task
    public static void taskKill(String strProcessName) {
        String strCmdLine = null;
        strCmdLine = String.format("TaskKill /F /IM " + strProcessName);
        Run.runCmd(strCmdLine);
    }

    //Holly shit! Don't use it! It can take down your pc!
    public static boolean taskKillExcept(String... except) {
        List<String> list = Run.taskList(except);
        if(list == null) {
            return false;
        }

        int len = list.size();
        String c;
        for(int i = 0; i < len; i++) {
            c = list.get(i);
            Run.taskKill(c);
        }
        c = null;
        return true;
    }

    public static List<String> taskList(String... except) {
        List<String> list = new ArrayList<String>();
        List<String> exc = new ArrayList<String>();

        int len = except.length;
        String c;
        for(int i = 0; i < len; i++) {
            c = except[i];
            if(c.endsWith("*")) {
                c = c.substring(0, c.length() - 1);
            }
            exc.add(c);
        }
        c = null;

        String out = Run.runCmd("TaskList");
        if(out == null) {
            System.err.println("Something went wrong.");
            return null;
        }
        String[] cmds = out.split("\n");
        len = cmds.length;
        int e;
        for(int i = 3; i < len; i++) {
            c = cmds[i];
            e = c.indexOf(' ');
            c = c.substring(0, e).trim();
            //System.out.println("Has: " + c);
            if(c.endsWith(".exe") && Run.isIn(exc, c) == false) {
                list.add(c);
            }
            exc.add(c);
        }
        c = null;


        return list;
    }


    /*** Utl ***/

    public static boolean isIn(List<String> arr, String what) {
        int len = arr.size();
        String c;
        for(int i = 0; i < len; i++) {
            c = arr.get(i);
            if(what.startsWith(c)) {
                return true;
            }
        }
        c = null;
        return false;
    }

    public static String runCmd(String cmd) {
        try {
            final Process p = Runtime.getRuntime().exec(cmd);
            final ProcessResultReader stderr = new ProcessResultReader(p.getErrorStream(), "STDERR");
            final ProcessResultReader stdout = new ProcessResultReader(p.getInputStream(), "STDOUT");
            stderr.start();
            stdout.start();
            final int exitValue = p.waitFor();
            if (exitValue == 0) {
                return stdout.toString();
            } else {
                return stderr.toString();
            }
        } catch (final Exception e) {
            e.printStackTrace();
        }
        return null;
    }


    /*** Run ***/

    public static void main(String... run) {
        System.out.println("Test: RunCmd: " + Run.runCmd("TaskList"));

        List<String> list = Run.taskList();
        System.out.println("Test: Process List: " + list);

        Run.taskKill();
    }
}

And

/*** Class ProcessResultReader.java from http://stackoverflow.com/questions/7637290/get-command-prompt-output-to-string-in-java ***/
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;

public class ProcessResultReader extends Thread {
    final InputStream is;
    final String type;
    final StringBuilder sb;

    ProcessResultReader(final InputStream is, String type) {
        this.is = is;
        this.type = type;
        this.sb = new StringBuilder();
    }

    public void run() {
        try {
            final InputStreamReader isr = new InputStreamReader(is);
            final BufferedReader br = new BufferedReader(isr);
            String line = null;
            while ((line = br.readLine()) != null) {
                this.sb.append(line).append("\n");
            }
        } catch (final Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public String toString() {
        return this.sb.toString();
    }
}


来源:https://stackoverflow.com/questions/24545819/taskkill-command-implementation-using-java

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!