You can execute the ProcessBuilder and get the response from its Input Stream.
Sample Code :
public static void main(String[] args) throws IOException, InterruptedException
{
ProcessBuilder builder = new ProcessBuilder("cmd.exe", "/C", "netstat -n -o | findstr :6129");
Process process = builder.start();
process.waitFor();
printProcessStream(process.getInputStream());
}
private static void printProcessStream(InputStream inputStream) throws IOException
{
int bytesRead = -1;
byte[] bytes = new byte[1024];
String output = "";
while((bytesRead = inputStream.read(bytes)) > -1){
output = output + new String(bytes, 0, bytesRead);
}
System.out.println(" The netstat command response is \r\n"+output);
}
The "-a" argument for netstat causes the Process Builder to wait indefinitely. You will need to remove that. Additionally if you required to get the Error Stream then the following can be added.
printProcessStream(process.getErrorStream());
Once you get the response stream, you can parse the data and identify the PID to kill. Subsequently you can use the similar logic but changing the command, instead of netstat you can use the command "kill -9 $PID" to finally kill the process.