获取系统所有进程列表,遍历,然后进行模糊匹配,将匹配到的进程杀死!
package com.auguigu.jdk;
import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
public class Test {
public static void main(String[] args) {
SingleProcess.comfirmSingleProcess("excel");
}
}
class SingleProcess {
// public static Logger logger = Logger.getLogger(SingleProcess.class);
/**
* 确认进程,获取进程,杀死进程
* @param prefix 进程名前缀
*/
public static void comfirmSingleProcess(String prefix) {
if(prefix == null) {
throw new NullPointerException("The prefix is null,please check it!!");
}
// 声明文件读取流
BufferedReader out = null;
BufferedReader br = null;
try {
// 创建系统进程
ProcessBuilder pb = new ProcessBuilder("tasklist");
Process p = pb.start();
// 读取进程信息
out = new BufferedReader(new InputStreamReader(new BufferedInputStream(p.getInputStream()), Charset.forName("GB2312")));
br = new BufferedReader(new InputStreamReader(new BufferedInputStream(p.getErrorStream())));
// 创建集合 存放 进程+pid
List<String> list = new ArrayList<>();
// 读取
String ostr;
while ((ostr = out.readLine()) != null){
// 将读取的进程信息存入集合
list.add(ostr);
}
// 遍历所有进程
for (int i = 3; i < list.size(); i++) {
// 必须写死,截取长度,因为是固定的
String process = list.get(i).substring(0, 25).trim(); // 进程名
String pid = list.get(i).substring(25, 35).trim(); // 进程号
// 匹配指定的进程名,若匹配到,则立即杀死
System.out.println("--->"+process.toLowerCase(Locale.ROOT));
if(process.toLowerCase(Locale.ROOT).startsWith(prefix)){
System.out.println("终止程序:"+process);
Process exec = Runtime.getRuntime().exec("taskkill /F /PID " + pid);
BufferedReader out1 = new BufferedReader(new InputStreamReader(new BufferedInputStream(exec.getInputStream()), Charset.forName("GB2312")));
String batResult = "";
String line = null;
// 直到读完为止
while ((line = out1.readLine()) != null) {
batResult += line+"\r\n";
}
if (batResult != "") {
//打印信息
System.out.println(batResult);
}
}
}
// 若有错误信息 即打印日志
String estr = br.readLine();
if (estr != null) {
System.out.println(estr);
// logger.error(estr);
}
} catch (IOException e) {
e.printStackTrace();
}finally {
// 关流
try {
if(out != null) { out.close(); }
} catch (IOException e) {
e.printStackTrace();
}
try {
if(br != null) { br.close(); }
} catch (IOException e) {
e.printStackTrace();
}
}
}
}