java中获取进程列表,进程id,进程名称,根据进程id或进程名称来杀进程 |
您所在的位置:网站首页 › java获取process进程id › java中获取进程列表,进程id,进程名称,根据进程id或进程名称来杀进程 |
咱们开门见山,代码如下,如有更好的办法,可以多多指教哦。。。。 import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.List; /** * * @author syp * */ public class KillProcess{ public static void main(String[] args) throws InterruptedException { /* * 下面先是获取进程列表 */ Runtime runtime = Runtime.getRuntime(); List tasklist = new ArrayList(); try { Process process = runtime.exec("tasklist"); BufferedReader br = new BufferedReader(new InputStreamReader(process.getInputStream())); String s = ""; while ((s = br.readLine()) != null) { if ("".equals(s)) { continue; } tasklist.add(s+" "); } // 获取每列最长的长度 String maxRow = tasklist.get(1) + ""; String[] maxCol = maxRow.split(" "); // 定义映像名称数组 String[] taskName = new String[tasklist.size()]; // 定义 PID数组 String[] taskPid = new String[tasklist.size()]; // 会话名数组 String[] taskSessionName = new String[tasklist.size()]; // 会话#数组 String[] taskSession = new String[tasklist.size()]; // 内存使用 数组 String[] taskNec = new String[tasklist.size()]; for (int i = 0; i < tasklist.size(); i++) { String data = tasklist.get(i) + ""; for (int j = 0; j < maxCol.length; j++) { switch (j) { case 0: taskName[i]=data.substring(0, maxCol[j].length()+1); data=data.substring(maxCol[j].length()+1); break; case 1: taskPid[i]=data.substring(0, maxCol[j].length()+1); data=data.substring(maxCol[j].length()+1); break; case 2: taskSessionName[i]=data.substring(0, maxCol[j].length()+1); data=data.substring(maxCol[j].length()+1); break; case 3: taskSession[i]=data.substring(0, maxCol[j].length()+1); data=data.substring(maxCol[j].length()+1); break; case 4: taskNec[i]=data; break; } } } int count=0; for (int i = 0; i < taskNec.length; i++) { //打印进程列表 //System.out.println(taskName[i]+" "+taskPid[i]+" "+taskSessionName[i]+" "+taskSession[i]+" "+taskNec[i]); //在此处我是根据获取进程名称来杀掉360se.exe这个进程的,你们可以按照你们得需求来写,按照进程名称或进程id来杀进程 if(taskName[i].contains("360se.exe")) { count++;//用于进程计数 } } //当进程数大于等于2个以上时,要求杀掉 if(count>=2) { Process p = null; try { //此处需要填写你要杀掉的进程名称 runtime.exec("cmd.exe /C start wmic process where name='360se.exe' call terminate"); } catch (IOException e) { e.printStackTrace(); } } } catch (Exception e) { e.printStackTrace(); } } }
以上代码,包含了获取进程列表及进程id,进程名称,进程内存使用,等杀完进程后可以在dos下验证,也可以打开资源管理器验证。 1.打开dos步骤如下: 1.win+R 2.cmd 3.输入tasklist 效果图: 2.打开资源管理器 Ctrl+Alt+Delete |
今日新闻 |
推荐新闻 |
CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3 |