Window java 扫描、查找、杀死进程

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

/**
 * Windows下java对进程的操作
 * Created by luoweijun on 2015/11/19.
 */
public class TaskHelp {
	/**
	 * @param args
	 */
	public static void main(String[] args) throws InterruptedException {
		// TODO Auto-generated method stub
		// startTask("E://Fetion//Fetion.exe");
		TaskHelp.killTask("nginx");
	}

	/**
	 * 杀死一个进程
	 *
	 * @param name    进程的名称,可前后模糊匹配
	 */
	public static void killTask(String name) {
		try {
			Process process = Runtime.getRuntime().exec("taskList");
			InputStream is = process.getInputStream();
			Scanner in = new Scanner(is);
			int count = 0;
			while (in.hasNextLine()) {
				count++;
				String s1 = in.nextLine();

				if (s1.contains(name)) {
					int c = s1.indexOf(" ", s1.indexOf(".exe"));
					String s2 = s1.substring(c, s1.length()).trim();
					String pid = s2.substring(0, s2.indexOf(" "));

					Runtime.getRuntime().exec("tskill " + pid);
				}
			}
			is.close();
			in.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}


	/**
	 * 查找Pid
	 *
	 * @param name
	 * @return 任务存在返回任务PID,任务不存在返回空字符
	 */
	public static String findPid(String name) {
		try {
			Process process = Runtime.getRuntime().exec("taskList");
			Scanner in = new Scanner(process.getInputStream());
			int count = 0;
			while (in.hasNextLine()) {
				count++;
				String s1 = in.nextLine();

				if (s1.contains(name)) {
					int c = s1.indexOf(" ", s1.indexOf(".exe"));
					String s2 = s1.substring(c, s1.length()).trim();
					String pid = s2.substring(0, s2.indexOf(" "));
					return pid;
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return "";
	}


	/**
	 * 显示当前机器的所有进程
	 */
	public static void showTaskList() {
		try {
			Process process = Runtime.getRuntime().exec("taskList");
			Scanner in = new Scanner(process.getInputStream());
			int count = 0;
			while (in.hasNextLine()) {
				count++;
				System.out.println(count + ":" + in.nextLine());
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * 启动一个进程
	 *
	 * @param task
	 */
	public static void startTask(String task) {
		try {
			Process p = Runtime.getRuntime().exec(task);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}


你可能感兴趣的:(Window java 扫描、查找、杀死进程)