java 打开和关闭串行端口

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6924516/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-30 17:54:39  来源:igfitidea点击:

Open and Close Serial Ports

javaserial-port

提问by S Gaber

I am trying to connect to a Serial Port... but once I open the Serial Portin the first time. I can't open it again, I've tried to apply. Here is my code:

我正在尝试连接到串行端口......但是一旦我Serial Port第一次打开它。我无法再次打开它,我已尝试申请。这是我的代码:

public static void main(String[] args) {
    portList = CommPortIdentifier.getPortIdentifiers();
    while (portList.hasMoreElements()) {
        portId = (CommPortIdentifier) portList.nextElement();
        if (portId.getPortType() == CommPortIdentifier.PORT_SERIAL) {
             if (portId.getName().equals("COM1")) {
                try {
                    serialPort = (SerialPort)
                        portId.open("SimpleWriteApp", 2000);
                } catch (PortInUseException e) {}
                try {
                    outputStream = serialPort.getOutputStream();
                } catch (IOException e) {}
                try {
                    serialPort.setSerialPortParams(9600,
                        SerialPort.DATABITS_8,
                        SerialPort.STOPBITS_1,
                        SerialPort.PARITY_NONE);
                } catch (UnsupportedCommOperationException e) {}
                try {
                    outputStream.write(messageString.getBytes());
                } catch (IOException e) {}
            }
        }
    }
}

I want to close that port so I can use it for another task.

我想关闭该端口,以便我可以将其用于其他任务。

回答by Manuel Selva

According to the java Communication API you just have to close()your serial port object:

根据java Communication API,您只需关闭()您的串行端口对象:

serialPort.close();

The close() method comes from the SerialPortsuper class CommPort.

close() 方法来自SerialPort超类CommPort

回答by sjpapa

serialPort.close(); works for me. Be careful not to use the port again before closing it, as a lock file is written to the /var/lock Linux directory. In windows something similar I presume. This file has to be deleted before reopening the port. Otherwise a nullPointerException will occur. Closing the port deletes this file.

serialPort.close(); 对我来说有效。注意在关闭之前不要再次使用端口,因为锁文件被写入 /var/lock Linux 目录。在 Windows 中,我认为类似的东西。在重新打开端口之前必须删除此文件。否则将发生 nullPointerException。关闭端口会删除此文件。