java-结束端口对应的process

发布时间 2023-08-25 18:00:40作者: hexuguang
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class ProcessKiller {
    public static void main(String[] args) {
        int port = 8080; // 要释放的端口号

        try {
            // 构造命令
            String command = "";
            String os = System.getProperty("os.name").toLowerCase(); // 获取操作系统名称

            if (os.contains("win")) {
                // Windows平台
                command = "cmd /c netstat -ano | findstr :" + port;
            } else if (os.contains("nix") || os.contains("nux") || os.contains("mac")) {
                // Linux或Mac平台
                command = "lsof -i :" + port;
            } else {
                System.out.println("不支持的操作系统");
                return;
            }

            // 执行命令
            Process process = Runtime.getRuntime().exec(command);

            // 读取命令输出
            BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
            String line;
            while ((line = reader.readLine()) != null) {
                // 获取进程ID
                String[] parts = line.trim().split("\\s+"); // 将行按空格切分
                String pid = parts[parts.length - 1];

                // 终止进程
                if (os.contains("win")) {
                    Runtime.getRuntime().exec("cmd /c taskkill /F /PID " + pid);
                } else if (os.contains("nix") || os.contains("nux") || os.contains("mac")) {
                    Runtime.getRuntime().exec("kill -9 " + pid);
                }

                System.out.println("已终止进程: " + pid);
            }

            // 关闭读取器
            reader.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}