comm.jar通信串口java

时间:2013-03-13 12:32:31

标签: java serial-port

我在使用comm.jar时遇到问题。

问题是我连接了设备,我使用此代码

在池中启动了应用程序
 public static void main(String[] args) {
        Enumeration portList;
        CommPortIdentifier portId = null;
        portList = CommPortIdentifier.getPortIdentifiers();
        while (portList.hasMoreElements()) {
            portId = (CommPortIdentifier) portList.nextElement();
            System.out.println("port::" + portId.getName());

        }
        while (true) {
            try {
                Thread.sleep(2000);
            } catch (InterruptedException ex) {
                Logger.getLogger(JavaComPortFinding.class.getName()).log(Level.SEVERE, null, ex);
            }
            main(args);
        }
    }

输出

port::COM1
port::COM10

经过一次民意调查后,我弹出了设备。我仍然得到了回复

port::COM1
port::COM10

任何人都可以帮助我/建议在投票中获得动态响应。

2 个答案:

答案 0 :(得分:1)

你可以尝试类似的东西,因为每次都应该重新创建CommPortIdentifier。

class TestProgram
{
    public static void main(String[] args)
    {
        while(true)
        {
            try
            {
                Thread.sleep(2000);
            }
            catch(InterruptedException ex)
            {
                Logger.getLogger(TestProgram.class.getName()).log(Level.SEVERE, null, ex);
            }

            scanPorts();
        }
    }

    private static void scanPorts()
    {
        Enumeration portList;
        CommPortIdentifier portId = null;
        portList = CommPortIdentifier.getPortIdentifiers();

        while (portList.hasMoreElements())
        {
            portId = (CommPortIdentifier) portList.nextElement();
            System.out.println("port::" + portId.getName());

        }
    }
}

编辑:

我刚刚在usb上使用黑莓手机测试了Windows XP SP3上的程序。当我启动程序时,我看到了BlackBerry的普通COM1和两个COM端口。断开BlackBerry连接后,端口将保留在设备管理器中。如果我手动删除它们,它们会在程序中消失(不重新启动)。

答案 1 :(得分:0)

https://community.oracle.com/thread/2063873?start=0&tstart=0

I found the above resource extremely valuable while finding solution for a similar issue.

The main problem here is that static block in CommPortIdentifier gets loaded only once and caches the ports information in field variable portList. When you call the getPortIdentifiers() method, it will return the ports from portList which were detected during the initial load.

The workaround this would be to reload the static block in CommPortIdentifier class and then call getPortIdentifiers(), which will reload the drivers and give you an updated list of COM ports (this was done using Java Reflection API in the link referenced).

Good Luck!