windows根据端口号杀死对应进程
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
public class CmdExecExample {
public final static String closePort="48081";
public static void main(String[] args) {
try {
ProcessBuilder processBuilder = new ProcessBuilder("cmd.exe", "/c", "netstat -aon|findstr "+closePort);
processBuilder.redirectErrorStream(true);
Process process = processBuilder.start();
InputStream inputStream = process.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, "GBK"));
String line;
while ((line = reader.readLine()) != null) {
String wordToFind = "LISTENING";
String dealStr=line.trim().replace(" ","");
dealStr=dealStr.trim();
int index = dealStr.indexOf(wordToFind);
if (index == -1) {
System.out.println("Word not found.");
} else {
System.out.println("Word found at index: " + index);
String realStr= dealStr.substring(index);
String cport=realStr.replace("LISTENING","").trim();
System.out.println("端口号:"+cport);
closePort(cport);
}
System.out.println(dealStr);
System.out.println(line);
break;
}
process.waitFor();
} catch (IOException | InterruptedException e) {
e.printStackTrace();
}
}
public static void closePort(String port) {
String cmd="taskkill -pid "+port+" -f";
try {
ProcessBuilder processBuilder = new ProcessBuilder("cmd.exe", "/c", cmd);
processBuilder.redirectErrorStream(true);
Process process = processBuilder.start();
InputStream inputStream = process.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, "GBK"));
String line;
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
process.waitFor();
} catch (IOException | InterruptedException e) {
e.printStackTrace();
}
}
}