本文介绍了使用JAVA的TASKKILL命令实现的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

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

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.

推荐答案

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

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').

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

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

还有

/*** 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的TASKKILL命令实现的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-23 19:40