Java 执行 Windows 中 cmd 命令, 并获取电脑主板 smBLOD_UUID 值

Java 执行 Windows 中 cmd 命令, 并获取电脑主板 smBIOD_UUID 值

1. 工具类

package com.monitor.common.util;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;

public class ExecCmd implements Runnable {
    private String command;
    private List<String> comment;

    public List<String> getComment() {
        return comment;
    }

    public ExecCmd(String command) {
        this.command = command;
    }

    @Override
    public void run() {
        Process process;
        int exitVal = 0;
        try {
            process = Runtime.getRuntime().exec(command);
            // Runtime.exec() 创建的子进程公用父进程的流, 不同平台上, 父进程的 stream buffer 可能被打满导致子进程阻塞, 从而永远无法返回.
            // 针对这种情况, 我们只需要将子进程的 stream 重定向出来即可.
            CmdStreamThread info = new CmdStreamThread(process.getInputStream(), "INFO");
            info.start();

            exitVal = process.waitFor();
            // 返回执行后的内容
            comment = info.getList_data();
        } catch (IOException | InterruptedException e) {
            e.printStackTrace();
        }

        if (exitVal != 0) {
            throw new RuntimeException("cmd任务执行失败");
        }
    }

    class CmdStreamThread extends Thread {
        private InputStream is;
        private String printType;
        private List<String> list_data;

        CmdStreamThread(InputStream is, String printType) {
            this.is = is;
            this.printType = printType;
        }

        List<String> getList_data() {
            return list_data;
        }

        public void run() {
            try {
                InputStreamReader isr = new InputStreamReader(is);
                BufferedReader br = new BufferedReader(isr);
                List<String> data_ = new ArrayList<>();
                String line;
                while ((line = br.readLine()) != null) {
                    System.out.println(printType + ">" + line);
                    if(!"".equals(line)) {
                        data_.add(line);
                    }
                }
                list_data = data_;
            } catch (IOException ioe) {
                ioe.printStackTrace();
            }
        }
    }
}

2. 运行

获取主板 UUID 的 cmd 命令

wmic csproduct get uuid

在这里插入图片描述

    @Test
    void smBIOS_UUID() {
        // 执行 cmd 获取主板 BIOS UUID
        ExecCmd execCmd = new ExecCmd("wmic csproduct get uuid");
        execCmd.run();
        System.out.println(execCmd.getComment().get(1).replaceAll("[ \t\n]*", ""));
    }

结果

在这里插入图片描述

  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值