当前拥有的javax.comm.portinuseexception端口

时间:2015-01-09 06:46:04

标签: java serial-port comm disconnection

我已经制作了一个通过rs232连接到设备的程序。这一切都很好,直到我关闭连接并尝试从同一个应用程序再次重新打开它。我得到以下异常:

javax.comm.PortInUseException: Port currently owned by controller.Application
        at javax.comm.CommPortIdentifier.open(CommPortIdentifier.java:310)
        at controller.Application.connect(Application.java:30)
        at controller.Application.send(Application.java:63)

当我完全关闭我的应用程序并重新启动它时,我可以再次连接到该端口。但我需要再次使用该端口而不关闭我的整个应用程序。 我试图关闭我的端口,如下所示,但它不能正常工作:

public void disconnect() {
        if (serialPort != null) {
            try {
                in.close();
                out.close();
                serialPort.removeEventListener();
                serialPort.close();
                commPort.close();
            } catch (Exception ex) {
                System.out.println("When closing: " + ex);
            }
        }

    }

我应该如何关闭我的端口以避免此异常?

1 个答案:

答案 0 :(得分:0)

您可以使用

                    if (serialPort != null)
                    {
                        serialPort.close();
                    }

我希望它会有所帮助