try {
Enumeration portList = CommPortIdentifier.getPortIdentifiers()
while (portList.hasMoreElements())
{
CommPortIdentifier portId = (CommPortIdentifier) portList.nextElement()
if (portId.getPortType() == CommPortIdentifier.PORT_SERIAL)//如果端口类型是串口则判断名称
{
if(portId.getName().equals("COM1")){//如果是COM1端口则退出循环
break
}else{
portId=null
}
}
}
SerialPort serialPort = (SerialPort)portId.open("Serial_Communication", 1000)//打开串口的超时时间为1000ms
serialPort.setSerialPortParams(9600,SerialPort.DATABITS_8,SerialPort.STOPBITS_1,SerialPort.PARITY_NONE)//设置串口速率为9600,数据位8位,停止位1们,奇偶校验无
InputStream in = serialPort.getInputStream()//得到输入流
OutputStream out = serialPort.getOutputStream()//得到输出流
//进行输入输出操作
//操作结束后
in.close()
out.close()
serialPort.close()//关闭串口
} catch (PortInUseException e) {
e.printStackTrace()
} catch (UnsupportedCommOperationException e) {
e.printStackTrace()
} catch (IOException e) {
e.printStackTrace()
}
}
配置好串口环境,不然在设备管理器里看到串口,用java也是读取不到串口的。还有有时候你配置好环境,运行之后也能列出串口。但过一段时间后,找不到串口了,然而在设备管理器里还能看到串口,以前也能运行,环境不存在问题,重启也没用。你可以这样解决,把win32com.dll复制到eclipse项目目录下,然后在main方法一开始添加如下代码,下面这样不需要配置comm环境了
CommDriver driver = null
String driverName = "com.sun.comm.Win32Driver"
try {
driver = (CommDriver) Class.forName(driverName).newInstance()
driver.initialize()
} catch (InstantiationException | IllegalAccessException
| ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace()
}