有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

如何使用java初始化串行端口?

我知道这个问题已经被问过很多次了,我已经浏览了谷歌的前20名搜索结果,但我仍然无法让我的代码正常工作

portList = CommPortIdentifier.getPortIdentifiers();
System.out.println("portList... " + portList);
while (portList.hasMoreElements()) {
    portId = (CommPortIdentifier) portList.nextElement();
    if (portId.getPortType() == CommPortIdentifier.PORT_SERIAL) {
        System.out.println("port identified is Serial.. "+ portId.getPortType());
        if (portId.getName().equals("COM2")) {
            System.out.println("port identified is COM2.. "+ portId.getName());  
            SimpleRead reader = new SimpleRead();
        } else {
            System.out.println("unable to open port");
        }
    }else{
        System.out.println("pordId.PortType = "+portId.getPortType());
        System.out.println("CommPortIdentifier.PORT_SERIAL = "+CommPortIdentifier.PORT_SERIAL);
    }
}

我得到的结果是

run:

端口列表。。。javax。通信。CommPortEnumerator@18020cc 生成成功(总时间:0秒)

有人知道怎么回事吗?为什么portId没有更多的元素?程序没有进入while循环

提前感谢您阅读这篇文章


共 (1) 个答案

  1. # 1 楼答案

    我设法解决了这个问题。 我需要为javac将文件复制到以下位置。通信工作

    1) win32com.dll to directory : jdk1.7.0/bin
    2) javax.comm.properties to directory : jdk1.7.0/jre/lib
    3) comm.jar to directory : jdk1.7.0/lib
    

    现在输出是

    portList... javax.comm.CommPortEnumerator@9173ef
    port identified is Serial.. 1
    port identified is CO11.. COM11
    In SimpleRead() contructor
    Serial Port.. COM11
    Input Stream... com.sun.comm.Win32SerialInputStream@95c083
    ................
    port identified is Serial.. 1
    unable to open port
    pordId.PortType = 2
    CommPortIdentifier.PORT_SERIAL = 1
    pordId.PortType = 2
    CommPortIdentifier.PORT_SERIAL = 1
    ending main
    In run() function