You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Java 8中获取Windows 10运行进程的命令行信息?

Java 8下获取Windows进程命令行并筛选终止的解决方案

在Windows环境下,要可靠获取进程的命令行信息,最直接的方式是调用系统原生的wmic命令——它能直接从WMI(Windows Management Instrumentation)中读取完整的进程元数据,包括命令行。以下是具体实现步骤和代码:

核心思路

通过执行wmic process命令查询目标进程的PID和命令行,解析输出后筛选符合条件的进程,再用taskkill终止。

1. 执行WMI命令获取进程信息

使用wmic process where "name='notepad.exe'" get ProcessId,CommandLine /format:csv命令,指定CSV格式输出(避免原始输出中大量空格的干扰):

  • 替换notepad.exe为你要查询的进程名称
  • /format:csv会输出表头和每行的PID、命令行,格式类似:Node,ProcessId,CommandLine

2. 解析命令输出

读取命令的输入流时注意:Windows命令行输出默认是GBK编码,需要指定编码避免乱码。然后逐行解析CSV内容,跳过表头行,提取每个进程的PID和命令行。

3. 筛选并终止进程

检查每个进程的命令行是否包含目标内容,若符合则执行taskkill /pid [PID] /f强制终止。

完整代码示例

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.List;

public class ProcessManager {

    // 存储进程信息的实体类
    static class ProcessInfo {
        private long pid;
        private String commandLine;

        public ProcessInfo(long pid, String commandLine) {
            this.pid = pid;
            this.commandLine = commandLine;
        }

        public long getPid() {
            return pid;
        }

        public String getCommandLine() {
            return commandLine;
        }
    }

    public static void main(String[] args) {
        String targetProcessName = "notepad.exe";
        String keyword = "thisisatest"; // 要匹配的命令行内容

        try {
            // 1. 获取目标进程的PID和命令行
            List<ProcessInfo> processList = getProcessesWithCommandLine(targetProcessName);

            // 2. 筛选符合条件的进程并终止
            for (ProcessInfo info : processList) {
                if (info.getCommandLine() != null && info.getCommandLine().contains(keyword)) {
                    System.out.printf("终止进程 PID: %d, 命令行: %s%n", info.getPid(), info.getCommandLine());
                    killProcess(info.getPid());
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 获取指定名称进程的PID和命令行信息
     */
    private static List<ProcessInfo> getProcessesWithCommandLine(String processName) throws IOException {
        List<ProcessInfo> result = new ArrayList<>();
        // 构造wmic命令,查询指定进程的PID和命令行,CSV格式输出
        String command = String.format("wmic process where \"name='%s'\" get ProcessId,CommandLine /format:csv", processName);

        ProcessBuilder pb = new ProcessBuilder("cmd.exe", "/c", command);
        Process process = pb.start();

        // 读取命令输出,Windows默认GBK编码
        try (BufferedReader reader = new BufferedReader(
                new InputStreamReader(process.getInputStream(), Charset.forName("GBK")))) {

            String line;
            boolean isHeader = true;
            while ((line = reader.readLine()) != null) {
                line = line.trim();
                if (line.isEmpty()) continue;

                if (isHeader) {
                    isHeader = false;
                    continue; // 跳过表头行
                }

                // 解析CSV行,格式:[计算机名],[PID],[命令行]
                String[] parts = line.split(",", 3); // 分割为3部分,避免命令行中的逗号干扰
                if (parts.length >= 2) {
                    try {
                        long pid = Long.parseLong(parts[1].trim());
                        String commandLine = parts.length == 3 ? parts[2].trim() : null;
                        result.add(new ProcessInfo(pid, commandLine));
                    } catch (NumberFormatException e) {
                        // 忽略无效的PID行
                        continue;
                    }
                }
            }
        }

        process.destroy();
        return result;
    }

    /**
     * 强制终止指定PID的进程
     */
    private static void killProcess(long pid) throws IOException {
        String command = String.format("taskkill /pid %d /f", pid);
        Process process = Runtime.getRuntime().exec(command);
        // 等待命令执行完成
        try {
            process.waitFor();
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
        }
        process.destroy();
    }
}

关键说明

  • 编码处理:Windows命令行输出默认是GBK,读取输入流时指定Charset.forName("GBK"),避免中文或特殊字符乱码。
  • CSV解析:使用split(",", 3)限制分割次数,防止命令行中的逗号导致解析错误。
  • 权限问题:确保程序以足够权限运行(比如管理员权限),否则可能无法读取某些系统进程的命令行,或无法终止进程。
  • 替代方案:如果wmic命令执行慢,可以改用PowerShell命令,但Java 8调用PowerShell需要处理输出格式,复杂度稍高,wmic更直接。

内容的提问来源于stack exchange,提问作者Neph

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.23 10:20:07