直接cmd 窗口执行如下命令即可
netstat -ano | findstr :8080
taskkill /F /PID <PID>
简简单单的两个指令,总是记不住,也懒的记, 每次端口冲突的时候, 都是直接查百度,很苦逼, 如果有一个程序,直接输入端口号,点击按钮直接杀死进程,岂不爽歪歪.
跟我一起制作一个屠猫的程序吧!
环境: 默认你已经安装了jdk
第一步: 在某个盘符里,新建一个文件夹, 并将以下文件KillTomcatProcess.java
放到文件夹中
KillTomcatProcess.java
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.BufferedReader;
import java.io.InputStreamReader; public class KillTomcatProcess extends JFrame { private JTextField portField; private JButton killButton; public KillTomcatProcess() { setTitle("Tomcat Port Killer"); setSize(300, 150); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setLocationRelativeTo(null); // Center the window setLayout(new FlowLayout()); JLabel label = new JLabel("Enter Tomcat Port:"); add(label); portField = new JTextField(10); add(portField); killButton = new JButton("Kill Process"); killButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { String port = portField.getText().trim(); if (!port.isEmpty()) { try { String pid = findProcessIdByPort(port); if (pid != null) { killProcess(pid); JOptionPane.showMessageDialog(KillTomcatProcess.this, "Process with PID " + pid + " killed successfully!"); } else { JOptionPane.showMessageDialog(KillTomcatProcess.this, "No process found for port " + port); } } catch (Exception ex) { JOptionPane.showMessageDialog(KillTomcatProcess.this, "Error: " + ex.getMessage()); } } else { JOptionPane.showMessageDialog(KillTomcatProcess.this, "Please enter a port number."); } } }); add(killButton); setVisible(true); } private String findProcessIdByPort(String port) throws Exception { String line; Process process = Runtime.getRuntime().exec("cmd /c netstat -aon | findstr " + port); BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream())); while ((line = reader.readLine()) != null) { if (line.contains("LISTENING")) { String[] parts = line.split("\\s+"); return parts[parts.length - 1];} } return null; } private void killProcess(String pid) throws Exception { Runtime.getRuntime().exec("cmd /c taskkill /F /PID " + pid); } public static void main(String[] args) { new KillTomcatProcess(); }
}
第二步:当前文件夹下打开cmd,将java文件编译成可执行文件javac KillTomcatProcess.java
尝试执行编译后的文件java KillTomcatProcess
窗口能够正常弹出即可,
现在输入端口能够立刻将进程杀死,但是操作起来一点也不方便
第三步: 在当前文件夹下,创建一个KillTomcat.bat
文件,文件内容如下
KillTomcat.bat
@echo off
java KillTomcatProcess
pause
鼠标右键,将该文件发送到桌面快捷方式,这样我们桌面上只有屠猫的图标,非常简洁