java获取计算机串口名列表

根据自有命令,Windows最简单的方法是注册表,linux最简单的方法是dmesg命令

实现如下

@Log4j2
public class ComPortScanUtil {

    // 检测系统中可用的通讯端口类
    private CommPortIdentifier commPortId;


    public static List<String> getComPorts() {
        /*String os = System.getProperty("os.name").toUpperCase();
        if ("LINUX".equals(os)) {
            return getComPortsLinux();
        } else {
            return getComPortsWindows();
        }*/
        return getComPortsByRxtx();
    }

    public static List<String> getComPortsByRxtx() {
        List<String> result = new ArrayList<>();
        // 获取系统中所有的通讯端口
        Enumeration<CommPortIdentifier> portList = CommPortIdentifier.getPortIdentifiers();
        // 循环通讯端口
        while (portList.hasMoreElements()) {
            CommPortIdentifier commPortId = portList.nextElement();
            // 判断是否是串口
            if (commPortId.getPortType() == CommPortIdentifier.PORT_SERIAL) {
                // 比较串口名称是否是指定串口
                result.add(commPortId.getName());
            }
        }
        return result;
    }

    public static List<String> getComPortsWindows() {

        List<String> ports = new ArrayList<>();

        try {
            String command = "reg query HKEY_LOCAL_MACHINE\\HARDWARE\\DEVICEMAP\\SERIALCOMM";
            Process process = Runtime.getRuntime().exec(command);
            InputStream in = process.getInputStream();
            BufferedReader br = new BufferedReader(new InputStreamReader(in));
            String line;
            int index = 0;
            while ((line = br.readLine()) != null) {
                if (line == null || "".equals(line)) {
                    continue;
                }

                if (index != 0) {
                    String[] strs = line.replaceAll(" +", ",").split(",");
                    String comPort = strs[strs.length - 1];
                    ports.add(comPort);
                }
                index++;

            }

        } catch (Exception e) {
            e.printStackTrace();
        }

        return ports;

    }

    public static List<String> getComPortsLinux() {
        List<String> list = new ArrayList<>();
        String devpath = "/dev/";
        String cmd = "dmesg";
        String execResult = executeLinuxCmd(cmd);
        log.warn("execResult={}", execResult);
        String[] infos = execResult.split("\\s+");
        log.warn("infos={}", infos);
        Set<String> ttys = new HashSet<>();
        for (String info : infos) {
            if (info.contains("ttyS") || info.contains("ttyU")) {
                String info2 = info.replace("[", "").replace(":", "").replace("]", "");
                String ttyPath = devpath + info2;

                File file = new File(ttyPath);
                if (file.exists()) {
                    log.warn("file={} 存在", ttyPath);
                    ttys.add(ttyPath);
                } else {
                    log.warn("file={} 不存在", ttyPath);
                }
            }
        }
        log.warn("ttys={}", ttys);
        list = Lists.newArrayList(ttys);
        return list;
    }

    /***************************linux*********************************/

    public static String executeLinuxCmd(String cmd) {
        try {
            System.out.println("got cmd job : " + cmd);
            Runtime run = Runtime.getRuntime();
            Process process;
            process = run.exec(cmd);
            InputStream in = process.getInputStream();
            BufferedReader bs = new BufferedReader(new InputStreamReader(in));
            StringBuffer out = new StringBuffer();
            byte[] b = new byte[8192];
            for (int n; (n = in.read(b)) != -1; ) {
                out.append(new String(b, 0, n));
            }

            in.close();
            process.destroy();
            return out.toString();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }


    public static void main(String[] args) {

        String os = System.getProperty("os.name").toUpperCase();

        if ("LINUX".equals(os)) {
            System.out.println(getComPortsLinux());
        } else {
            System.out.println(getComPortsWindows());
        }

    }

}

实现完成之后,发现rxtx包有更简单的方式 CommPortIdentifier.getPortIdentifiers()

关键代码

  public static List<String> getComPortsByRxtx() {
        List<String> result = new ArrayList<>();
        // 获取系统中所有的通讯端口
        Enumeration<CommPortIdentifier> portList = CommPortIdentifier.getPortIdentifiers();
        // 循环通讯端口
        while (portList.hasMoreElements()) {
            CommPortIdentifier commPortId = portList.nextElement();
            // 判断是否是串口
            if (commPortId.getPortType() == CommPortIdentifier.PORT_SERIAL) {
                // 比较串口名称是否是指定串口
                result.add(commPortId.getName());
            }
        }
        return result;
    }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值