62,628
社区成员
发帖
与我相关
我的任务
分享
package com.hemin.killpro;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
public class KillPro {
public static void main(String[] args) {
String port = "9999";
List<String > list = new ArrayList<>();
String pid=null;
Runtime run =Runtime.getRuntime();
Process pro = null;
//查询端口的pid
String commend = "cmd /c netstat -ano |findstr "+port;
try {
pro = run.exec(commend);
BufferedReader bf = new BufferedReader(new InputStreamReader(pro.getInputStream()));
String line = null;
while((line = bf.readLine())!=null){
//System.out.println(line);
list.add(line);
}
} catch (Exception e) {
e.printStackTrace();
}
//判断是否存在指定端口
if(list.size()==0){
System.out.println("指定端口没有被使用!");
}else{
for (String str : list) {
String ip = str.split(" +")[2];
int beg = ip.lastIndexOf(':')+1;
int end = ip.length();
String destport = ip.substring(beg, end);
if(destport.equals(port)){
System.out.println(str.split(" +")[5]);
pid = str.split(" +")[5];
break;
}
}
if(pid ==null){
System.out.println("没有对应端口没有被使用!");
}else{
//kill port
String command ="cmd /c taskkill /pid "+port+" /F";
try {
pro = run.exec(command);
} catch (IOException e) {
e.printStackTrace();
}finally {
System.out.println("以杀掉占用程序");
}
}
}
}
}