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.nextEl开发者_运维问答ement();
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.
精彩评论