Java 原生不支援串口,需引入第三方庫。目前主流選擇:
Maven 依賴:
<dependency>
<groupId>com.fazecast</groupId>
<artifactId>jSerialComm</artifactId>
<version>2.10.4</version>
</dependency>
核心程式碼:
import com.fazecast.jSerialComm.*;
public class SerialDemo {
public static void main(String[] args) {
SerialPort[] ports = SerialPort.getCommPorts();
if (ports.length == 0) { System.out.println("無可用串口"); return; }
SerialPort port = ports[0]; // 選擇第一個
port.setBaudRate(9600);
port.setNumDataBits(8);
port.setNumStopBits(1);
port.setParity(SerialPort.NO_PARITY);
port.setFlowControl(SerialPort.FLOW_CONTROL_DISABLED);
if (!port.openPort()) { System.out.println("開啟失敗"); return; }
System.out.println("串口已開啟:" + port.getSystemPortName());
// 發送
String cmd = "*IDN?\n";
port.getOutputStream().write(cmd.getBytes());
port.getOutputStream().flush();
// 接收 (簡易輪詢,生產環境建議用事件監聽)
new Thread(() -> {
byte[] buffer = new byte[1024];
while (port.isOpen()) {
int len = port.getInputStream().read(buffer);
if (len > 0) {
System.out.println("收到:" + new String(buffer, 0, len));
}
}
}).start();
// 測試用:10 秒後關閉
try { Thread.sleep(10000); } catch (InterruptedException ignored) {}
port.closePort();
}
}
rxtxSerial.dll (Windows) / librxtxSerial.so (Linux) 放入 java.library.path。gnu.io.CommPortIdentifier。dialout 群組:sudo usermod -a -G dialout $USER。read() 導致執行緒卡死,使用 addDataListener (jSerialComm) 或獨立執行緒 + 超時機制。新專案強烈推薦 jSerialComm,部署單一 JAR 即可,無原生庫頭痛問題。