下面通过纯 Java 代码实现获取本机串口列表功能,通过查询注册表信息来实现。代码如下:
import java.io.BufferedReader; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.List; /** * 串口工具类 * * @author hxstrive.com */ public class ComPortTools { /** * 通过注册表的方式去获取串口列表 * * @return 串口名称 List */ public static List<String> getComPorts() { List<String> ports = new ArrayList<String>(); BufferedReader br = null; try { // 命令,执行改命令的示例: // C:\Users\Administrator> reg query HKEY_LOCAL_MACHINE\HARDWARE\DEVICEMAP\SERIALCOMM // // HKEY_LOCAL_MACHINE\HARDWARE\DEVICEMAP\SERIALCOMM // \Device\VSerial_1 REG_SZ COM2 // \Device\VSerial_0 REG_SZ COM1 String command = "reg query HKEY_LOCAL_MACHINE\\HARDWARE\\DEVICEMAP\\SERIALCOMM"; Process process = Runtime.getRuntime().exec(command); br = new BufferedReader(new InputStreamReader(process.getInputStream())); String line; int index = 0; while ((line = br.readLine()) != null) { if ("".equals(line)) { continue; } if (index != 0) { String[] strs = line.split("\\s+"); String comPort = strs[strs.length - 1]; ports.add(comPort); } index++; } } catch (Exception e) { e.printStackTrace(); } finally { if(null != br) { try { br.close(); } catch (Exception e) { e.printStackTrace(); } } } return ports; } }
先看看本机的串口信息,如下图:
测试代码如下:
import org.junit.Test; import java.util.List; /** * ComPortTools 测试 * * @author hxstrive.com */ public class ComPortToolsTest { @Test public void getComPorts() { List<String> ports = ComPortTools.getComPorts(); for(String port : ports) { System.out.println(port); } // 结果: // COM2 // COM1 } }