Java 打开和关闭串行端口
我正在尝试连接到。。。但是一旦我第一次打开Java 打开和关闭串行端口,java,serial-port,Java,Serial Port,我正在尝试连接到。。。但是一旦我第一次打开串行端口。我不能再打开了,我已经试着申请了。这是我的密码: public static void main(String[] args) { portList = CommPortIdentifier.getPortIdentifiers(); while (portList.hasMoreElements()) { portId = (CommPortIdentifier) portList.nextElement();
串行端口
。我不能再打开了,我已经试着申请了。这是我的密码:
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) {}
}
}
}
}
我想关闭该端口,以便将其用于另一项任务。根据java通信API,您只需连接到串行端口对象即可:
serialPort.close();
close()方法来自SerialPort
super类CommPort
SerialPort.close();对我有用。在关闭端口之前,请注意不要再次使用该端口,因为锁文件会写入/var/lock Linux目录。我猜在窗户里也有类似的东西。在重新打开端口之前,必须删除此文件。否则将发生nullPointerException。关闭端口将删除此文件