需要注意的是导入jar包后还需要在classpath下放好rxtxParallel.dll
和rxtxSerial.dll
(或者放到PATH下)。
import gnu.io.*;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.util.Enumeration;
import java.util.HashSet;
public class ComHelper {
public static HashSet<CommPortIdentifier> getAvailableSerialPorts() {
HashSet<CommPortIdentifier> h = new HashSet<>();
Enumeration<CommPortIdentifier> portList = CommPortIdentifier.getPortIdentifiers();
while (portList.hasMoreElements()) {
CommPortIdentifier com = portList
.nextElement();
switch (com.getPortType()) {
case CommPortIdentifier.PORT_SERIAL:
try {
//open:(应用程序名【随意命名】,阻塞时等待的毫秒数)
/*open 方法打开通讯端口,获得一个 CommPort 对象,它使程序独占端口。
如果端口正被其他应用程序占用,将使用 CommPortOwnershipListener 事件机制
传递一个 PORT_OWNERSHIP_REQUESTED 事件。
每个端口都关联一个 InputStream 和一个 OutputStream,如果端口是用
open 方法打开的,那么任何的 getInputStream 都将返回相同的数据流对象,除非
有 close 被调用。
*/
CommPort thePort = com.open(Object.class.getSimpleName(), 50);
thePort.close();
h.add(com);
} catch (PortInUseException e) {
//不可用串口
System.out.println("Port, " + com.getName()
+ ", is in use.");
} catch (Exception e) {
System.err.println("Failed to open port " + com.getName());
e.printStackTrace();
}
}
}
return h;
}
public static SerialPort openComm(String commStr){
HashSet<CommPortIdentifier> portSet = ComHelper.getAvailableSerialPorts();
SerialPort serialPort=null;
for (CommPortIdentifier comm : portSet) {
if (comm.getName().equals(commStr)) {
try {
// open:(应用程序名【随意命名】,阻塞时等待的毫秒数)
serialPort = (SerialPort) comm.open("whatever",
2000);
serialPort.notifyOnDataAvailable(true);
// 这里定义了波特率,数据位,停止位,校验位
serialPort.setSerialPortParams(9600, SerialPort.DATABITS_8,
SerialPort.STOPBITS_1, SerialPort.PARITY_NONE);
break;
} catch (PortInUseException e) {
e.printStackTrace();
} catch (UnsupportedCommOperationException e) {
e.printStackTrace();
}
}
}
return serialPort;
}
public static String readData(SerialPort serialPort){
String str="";
try {
if(serialPort!=null){
InputStream inputStream = serialPort.getInputStream();
ByteArrayOutputStream baos = new ByteArrayOutputStream();
int i;
while ((i = inputStream.read()) != -1) {
baos.write(i);
}
str = baos.toString();
}
} catch (Exception e) {
e.printStackTrace();
logger.error(e.getMessage());
}
return str;
}
}
使用方法:
SerialPort serialPort = ComHelper.openComm("COM4");
while (true) {
String comdata = ComHelper.readData(serialPort);
}