简体   繁体   中英

Open and Close Serial Ports

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

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.

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

serialPort.close();

The close() method comes from the SerialPort super class CommPort .

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM