我有两种用JAVA编写的方法,taskkill()和taskkill(String strProcessName),如下所示:

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


我的问题是,程序运行时会杀死记事本和Matlab程序,并且计时器每隔3秒就会继续运行,以杀死这些文件(如果它们运行)。现在,我想在taskkill(String strProcessName)下使用“ ne”代替“ eq”,并希望杀死除记事本和matlab之外的所有程序。但是我没有这样做。请帮助我运行程序。

最佳答案

这个给你。您可以使用方法taskKill(String name)(杀死一个名称为“ name”的任务)和taskKillExcept(String... except)(杀死所有任务,除了参数“ except”中的任务)。

我测试了taskKill(String),但是没有测试taskKillExcept(String ...),它可以关闭您的电脑。

/*** 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();
    }
}




/*** 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();
    }
}

关于java - 使用JAVA实现TASKKILL命令,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/24545819/

10-12 04:02