Java 获取串口列表 不用任何第三方组件
之前用RXTX 获取串口列表的时候,如果串口被使用,就没法获取到了。
所以采用另外一种方式,利用注册表来获取所有串口列表
java
package com.zh.client.serial.utils;
import java.io.*;
import java.util.ArrayList;
import java.util.List;
/**
获取com端口,windows专用
/
public class ComPortScanUtil {
public static List<String> getComPorts() {
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 void main(String[] args) {
System.out.println(getComPorts());
}
}
package com.zh.client.serial.utils;
import java.io.*;
import java.util.ArrayList;
import java.util.List;
/**
获取com端口,windows专用
/
public class ComPortScanUtil {
public static List<String> getComPorts() {
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 void main(String[] args) {
System.out.println(getComPorts());
}
}