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

时间:2017-07-17 14:39:06

标签: java windows cmd

我是java和window的新手,我想杀死在特定端口上运行的进程。让我们说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");
}

1 个答案:

答案 0 :(得分:0)

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

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");
           }