我想在同一台笔记本电脑上读取和写入串行数据,然后尝试使用此代码。它工作正常,但选择端口是运行配置,如逐个选择COM1和COM2。然而;当我想以相同的方式再次使用端口时,出现NoSuchPortException错误,所以无论如何都要断开端口以进行第二次使用?
package javaSerial;
import java.util.Scanner;
import gnu.io.CommPortIdentifier;
import gnu.io.SerialPort;
public class RS232 {
public void connect(String portName) throws Exception {
CommPortIdentifier portIdentifier = CommPortIdentifier.getPortIdentifier(portName);
if (portIdentifier.isCurrentlyOwned()) {
System.out.println("Port in use!");
} else {
// points who owns the port and connection timeout
SerialPort serialPort = (SerialPort) portIdentifier.open("RS232Example", 2000);
// setup connection parameters
serialPort.setSerialPortParams(
38400, SerialPort.DATABITS_8, SerialPort.STOPBITS_1, SerialPort.PARITY_NONE);
// setup serial port writer
CommPortSender.setWriterStream(serialPort.getOutputStream());
// setup serial port reader
new CommPortReceiver(serialPort.getInputStream()).start();
}
}
public static void main(String[] args) throws Exception {
String textName;
int startIndex;
int byteLength;
Scanner scan = new Scanner(System.in);
System.out.println("textName");
textName = scan.nextLine();
System.out.println("startIndex");
startIndex = scan.nextInt();
System.out.println("byteLength");
byteLength = scan.nextInt();
// connects to the port which name (e.g. COM1) is in the first argument
new RS232().connect(args[0]);
// send HELO message through serial port using protocol implementation
CommPortSender.send(new ProtocolImpl().getMessage(new ReadFileIntoByteArray(textName, startIndex, byteLength).getFileString()));
}
}