Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to find the process id of a process running on a port number in java

Tags:

java

windows

cmd

I am new to java and window as well I want to kill the process which is running on a specific port. let's say 9090.

what I tried

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");
}
like image 872
digvijay dubey Avatar asked Dec 19 '25 16:12

digvijay dubey


1 Answers

This is What you want to do . I hope it will help you.

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");
           }
like image 153
Pavan Kumar Avatar answered Dec 22 '25 04:12

Pavan Kumar



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!