- 1 year ago
How to kill the running port number using java
Comment
1 / 1
To kill a process running on a specific port number using Java, you can use the ProcessBuilder
class to run a command to find and kill the process. On Windows, you can use the netstat
command to find the process ID (PID) associated with the specific port, and then use the taskkill
command to terminate the process.
Here's a Java method to kill a process running on a specific port:
javaimport java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class ProcessUtils {
public static void killProcessOnPort(int port) throws IOException {
// Run netstat command to get the process ID (PID) associated with the port
ProcessBuilder processBuilder = new ProcessBuilder("cmd.exe", "/c", "netstat -ano | findstr :" + port);
Process process = processBuilder.start();
try (BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()))) {
String line;
while ((line = reader.readLine()) != null) {
String[] columns = line.trim().split("\\s+");
if (columns.length >= 5) {
int pid = Integer.parseInt(columns[4]);
// Run taskkill command to terminate the process
ProcessBuilder killProcessBuilder = new ProcessBuilder("cmd.exe", "/c", "taskkill /F /PID " + pid);
Process killProcess = killProcessBuilder.start();
killProcess.waitFor();
}
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
int portNumberToKill = 8080; // Replace with the port number you want to kill
try {
killProcessOnPort(portNumberToKill);
System.out.println("Process running on port " + portNumberToKill + " is killed.");
} catch (IOException e) {
e.printStackTrace();
}
}
}
Please note that killing a process may lead to data loss or unexpected behavior, so use this approach with caution and only when necessary. Also, ensure that you have appropriate permissions to execute the taskkill
command on your system.