- 首先去
https://repo1.maven.org/maven2/
下载rxtx的jar包,比如下载rxtx-2.1.7.jar
放在项目的lib目录中
- 去这里
https://files-cdn.cnblogs.com/files/blogs/666773/rxtx-win-x64.rar
下载RXTXcomm.jar
(放在项目的lib中)、rxtxParallel.dll和rxtxSerial.dll
(放在项目的根目录中)
- 如下代码就是获取指定串口的数据
package sdf;
import gnu.io.CommPortIdentifier;
import gnu.io.SerialPort;
import gnu.io.SerialPortEvent;
import gnu.io.SerialPortEventListener;
import java.io.IOException;
import java.io.InputStream;
public class SerialPortReader implements SerialPortEventListener {
private SerialPort serialPort;
private InputStream inputStream;
public static void main(String[] args) {
SerialPortReader reader = new SerialPortReader();
reader.connect("COM1");
reader.readData();
}
public void connect(String portName) {
try {
CommPortIdentifier portIdentifier = CommPortIdentifier.getPortIdentifier(portName);
if (portIdentifier.isCurrentlyOwned()) {
System.out.println("Port is currently in use.");
} else {
serialPort = (SerialPort) portIdentifier.open("SerialPortReader", 2000);
serialPort.setSerialPortParams(9600, SerialPort.DATABITS_8, SerialPort.STOPBITS_1, SerialPort.PARITY_NONE);
inputStream = serialPort.getInputStream();
serialPort.addEventListener(this);
serialPort.notifyOnDataAvailable(true);
}
} catch (Exception e) {
e.printStackTrace();
}
}
public void readData() {
try {
while (true) {
Thread.sleep(1000);
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
@Override
public void serialEvent(SerialPortEvent event) {
if (event.getEventType() == SerialPortEvent.DATA_AVAILABLE) {
try {
byte[] buffer = new byte[inputStream.available()];
inputStream.read(buffer);
String data = new String(buffer);
System.out.println("Received data: " + data);
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
- 获取所有端口代码
import gnu.io.CommPortIdentifier;
import gnu.io.SerialPort;
import java.util.Enumeration;
public class SerialPortReader {
public static void main(String[] args) {
Enumeration portList = CommPortIdentifier.getPortIdentifiers();
while (portList.hasMoreElements()) {
CommPortIdentifier portId = (CommPortIdentifier) portList.nextElement();
if (portId.getPortType() == CommPortIdentifier.PORT_SERIAL) {
System.out.println(portId.getName());
}
}
String portName = "COM1";
try {
CommPortIdentifier portIdentifier = CommPortIdentifier.getPortIdentifier(portName);
if (portIdentifier.isCurrentlyOwned()) {
System.out.println("Port is currently in use.");
} else {
SerialPort serialPort = (SerialPort) portIdentifier.open("SerialPortReader", 2000);
serialPort.setSerialPortParams(9600, SerialPort.DATABITS_8, SerialPort.STOPBITS_1, SerialPort.PARITY_NONE);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}