javacomm20-win32.zip (或 RXTX rxtx-2.1-7-bins-r2.zip)win32com.dll → JDK/bin & JRE/bincomm.jar → JDK/lib & JRE/libjavax.comm.properties → JDK/lib & JRE/lib (內容:Driver=com.sun.comm.Win32Driver)COM1, COM3 等
public static void listPorts() {
Enumeration<CommPortIdentifier> ports = CommPortIdentifier.getPortIdentifiers();
while (ports.hasMoreElements()) {
CommPortIdentifier pid = ports.nextElement();
if (pid.getPortType() == CommPortIdentifier.PORT_SERIAL) {
System.out.println(pid.getName()); // COM1, COM2 ...
}
}
}
public class SerialPortManager {
private SerialPort port;
private InputStream in;
private OutputStream out;
public boolean open(String portName, int baudRate) {
try {
CommPortIdentifier pid = CommPortIdentifier.getPortIdentifier(portName);
port = (SerialPort) pid.open("MyApp", 2000); // 2s 超時
port.setSerialPortParams(baudRate,
SerialPort.DATABITS_8,
SerialPort.STOPBITS_1,
SerialPort.PARITY_EVEN);
port.setInputBufferSize(1024);
port.setOutputBufferSize(1024);
in = port.getInputStream();
out = port.getOutputStream();
port.notifyOnDataAvailable(true); // 事件驅動可選
return true;
} catch (Exception e) { e.printStackTrace(); return false; }
}
public void close() {
try { if (in != null) in.close(); } catch (IOException ignored) {}
try { if (out != null) out.close(); } catch (IOException ignored) {}
if (port != null) port.close();
}
}
public String readBlocking() throws IOException {
byte[] buf = new byte[4096];
int len = in.read(buf); // 阻塞直到有數據
if (len <= 0) return null;
byte[] data = Arrays.copyOf(buf, len);
return bytesToHex(data); // 轉十六進制字符串便於調試
}
port.addEventListener(new SerialPortEventListener() {
@Override public void serialEvent(SerialPortEvent e) {
if (e.getEventType() == SerialPortEvent.DATA_AVAILABLE) {
try { processInput(in); } catch (IOException ex) { ex.printStackTrace(); }
}
}
});
port.notifyOnDataAvailable(true);
public void send(byte[] data) throws IOException {
out.write(data);
out.flush();
}
in.read() 或事件回調處理接收byte[],單一發送線程串行 out.write() (避免並發寫入錯亂)jSerialComm (Fazecast) — 純 Java、無需原生庫安裝、跨平台、API 更簡潔,推薦新項目使用。