[英]Open and Close Serial Ports
我正在嘗試連接到串行端口 ......但是一旦我第一次打開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) {}
}
}
}
}
我想關閉該端口,以便我可以將它用於其他任務。
serialPort.close(); 適合我。 在關閉端口之前,請注意不要再次使用該端口,因為鎖定文件將寫入/ var / lock Linux目錄。 在Windows中我認為類似的東西。 在重新打開端口之前必須刪除此文件。 否則將發生nullPointerException。 關閉端口會刪除此文件。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.