如何在Java中查找运行在端口号上的进程的进程ID

3

我是一名新手,对Java和Windows都不熟悉。我想要结束运行在特定端口上的进程,比如说9090。

我尝试过:

try{
    Runtime rt = Runtime.getRuntime();
    Process proc = rt.exec("netstat -ano | findstr 9090");

    BufferedReader stdInput = new BufferedReader(
                                     new InputStreamReader(proc.getInputStream()));
    String s = null;

    if ((s = stdInput.readLine()) != null) {
        int index=s.lastIndexOf(" ");
        String sc=s.substring(index, s.length());

        rt.exec("Taskkill /PID" +sc+" /T /F");

    }
    JOptionPane.showMessageDialog(null, "Server Stopped");
}catch(Exception e){
    JOptionPane.showMessageDialog(null, "Something Went wrong with server");
}

2
请提供您执行上述代码时得到的输出/错误。 - Dhaval Simaria
1个回答

2

这就是你想要做的。我希望它能对你有所帮助。

try{
               Runtime rt = Runtime.getRuntime();
               Process proc = rt.exec("cmd /c netstat -ano | findstr 9090");

               BufferedReader stdInput = new BufferedReader(new
               InputStreamReader(proc.getInputStream()));
               String s = null;
               if ((s = stdInput.readLine()) != null) {
               int index=s.lastIndexOf(" ");
               String sc=s.substring(index, s.length());

               rt.exec("cmd /c Taskkill /PID" +sc+" /T /F");

       }
               JOptionPane.showMessageDialog(null, "Server Stopped");
         }catch(Exception e){
               JOptionPane.showMessageDialog(null, "Something Went wrong with server");
           }

请问同样的事情在 Mac 上也需要实现吗?我想要在 Mac 上关闭端口。 - Vikram Saini
@VikramSaini 这个解决方案使用Windows命令。 - golimar

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接