Java 如何通过CommPortIdentifier查找COM端口

Java 如何通过CommPortIdentifier查找COM端口,java,serial-port,modbus,Java,Serial Port,Modbus,我是全新的modbus和串行通信概念,所以即使这是一个真正的noob问题,也请容忍我 好的,我正在尝试使用modbus协议和RS232端口读取存储在寄存器上的值。我已经写了这段代码,但它找不到串口COM 4。我做错了什么 String wantedPortName = "COM 4" ; Enumeration portIdentifiers = CommPortIdentifier.getPortIdentifiers(); CommPortIdentifier portId = null

我是全新的modbus和串行通信概念,所以即使这是一个真正的noob问题,也请容忍我

好的,我正在尝试使用modbus协议和RS232端口读取存储在寄存器上的值。我已经写了这段代码,但它找不到串口COM 4。我做错了什么

String wantedPortName = "COM 4" ;

Enumeration portIdentifiers = CommPortIdentifier.getPortIdentifiers();

CommPortIdentifier portId = null;  
while (portIdentifiers.hasMoreElements()) {
    CommPortIdentifier pid = (CommPortIdentifier) portIdentifiers.nextElement();
    if (pid.getPortType() == CommPortIdentifier.PORT_SERIAL
            && pid.getName().equals(wantedPortName)) {
        portId = pid;
        break;
    }
}
if (portId == null) {
    System.err.println("Could not find serial port " + wantedPortName);
    System.exit(1);
}

看起来不错,请尝试在wantedPortName中不使用空白:

String wantedPortName = "COM4" ;
[已编辑]

你能试试这个吗

final CommPortIdentifier portId = CommPortIdentifier.getPortIdentifier("COM1");
System.err.println(portId.getName());

看起来不错,请尝试在wantedPortName中不使用空白:

String wantedPortName = "COM4" ;
[已编辑]

你能试试这个吗

final CommPortIdentifier portId = CommPortIdentifier.getPortIdentifier("COM1");
System.err.println(portId.getName());

在这种情况下,只有当引用相同时,equals才会返回true。因为您正在测试两个不同的字符串对象,所以它总是会失败。您必须改用compareTo:

if (pid.getPortType() == CommPortIdentifier.PORT_SERIAL
        && (pid.getName().compareTO(wantedPortName)==0) ) {
    portId = pid;
    break;
}

在这种情况下,只有当引用相同时,equals才会返回true。因为您正在测试两个不同的字符串对象,所以它总是会失败。您必须改用compareTo:

if (pid.getPortType() == CommPortIdentifier.PORT_SERIAL
        && (pid.getName().compareTO(wantedPortName)==0) ) {
    portId = pid;
    break;
}

我试过了,但它不起作用,事实上我也试过COM1,但它也不起作用;最终CommPortIdentifier portId=CommPortIdentifier.getPortIdentifierCOM1?我刚刚使用MODSCAN在我的电脑上测试了COM1和COM4端口,两个端口都正常工作。我尝试了,但都不正常。事实上,我也尝试了COM1,但也不正常。是否要我替换CommPortIdentifier portId=null;最终CommPortIdentifier portId=CommPortIdentifier.getPortIdentifierCOM1?我刚刚用MODSCAN在我的电脑上测试了COM1和COM4端口,两个端口都正常工作为什么会失败?wantedPortName和pid.getName都是字符串,string.equalsotherString工作正常。为什么equals会失败?wantedPortName和pid.getName都是字符串,string.equalsotherString工作正常。