java读写串⼝数据你了解多少
⽬录
1.导⼊⽀持java串⼝通信的jar包:
2.编写代码操作串⼝:
总结
最近接触到了串⼝及其读写,在此记录java进⾏串⼝读写的过程。
1.导⼊⽀持java串⼝通信的jar包:
在maven项⽬的l中添加RXTXcomm的依赖或者下载RXTXcomm.jar并导⼊到项⽬中。
⽀持Java串⼝通信操作的jar包,javam⽐较⽼,⽽且不⽀持64位系统,推荐使⽤Rxtx这个jar包(32位/64位均⽀持)。
下载地址:
注意:运⾏过程中抛出java.lang.UnsatisfiedLinkError错误或gnu.io下的类不到时,将rxtx解压包中的rxtxParallel.dll,rxtxSerial.dll 这两个⽂件复制到C:\Windows\System32 ⽬录下可解决该错误。
2.编写代码操作串⼝:
串⼝必要参数类:包含连接串⼝所必须的参数,⽅便在调⽤串⼝时设置和传递串⼝参数
/**
* 串⼝必要参数接收类
* @author: LinWenLi
* @date: 2018年7⽉21⽇下午4:30:40
*/
public class ParamConfig {
private String serialNumber;// 串⼝号
private int baudRate;        // 波特率
private int checkoutBit;    // 校验位
private int dataBit;        // 数据位
private int stopBit;        // 停⽌位
public ParamConfig() {}
/**
* 构造⽅法
* @param serialNumber    串⼝号
* @param baudRate        波特率
* @param checkoutBit    校验位
* @param dataBit        数据位
* @param stopBit        停⽌位
*/
public ParamConfig(String serialNumber, int baudRate, int checkoutBit, int dataBit, int stopBit) {
this.serialNumber = serialNumber;
this.baudRate = baudRate;
this.checkoutBit = checkoutBit;
this.dataBit = dataBit;
this.stopBit = stopBit;
}
getter()...
setter()...
}
串⼝操作类:(其中包含的CustomException是⾃定义异常类,仅⽤于抛出异常原因。)
import gnu.io.CommPortIdentifier;
import gnu.io.PortInUseException;
import gnu.io.SerialPort;
import gnu.io.SerialPortEvent;
import gnu.io.SerialPortEventListener;
import gnu.io.UnsupportedCommOperationException;
/**
* 串⼝参数的配置串⼝⼀般有如下参数可以在该串⼝打开以前进⾏配置:包括串⼝号,波特率,输⼊/输出流控制,数据位数,停⽌位和奇偶校验。
*/
// 注:串⼝操作类⼀定要继承SerialPortEventListener
public class SerialPortUtils implements SerialPortEventListener {
// 检测系统中可⽤的通讯端⼝类
private CommPortIdentifier commPortId;
// 枚举类型
private Enumeration<CommPortIdentifier> portList;
// RS232串⼝
private SerialPort serialPort;
// 输⼊流
private InputStream inputStream;
// 输出流
private OutputStream outputStream;
/
/ 保存串⼝返回信息
private String data;
// 保存串⼝返回信息⼗六进制
private String dataHex;/**
* 初始化串⼝
* @author LinWenLi
* @date 2018年7⽉21⽇下午3:44:16
* @Description: TODO
* @param: paramConfig  存放串⼝连接必要参数的对象(会在下⽅给出类代码)
* @return: void
* @throws
*/
@SuppressWarnings("unchecked")
public void init(ParamConfig paramConfig) {
// 获取系统中所有的通讯端⼝
portList = PortIdentifiers();
// 记录是否含有指定串⼝
boolean isExsist = false;
// 循环通讯端⼝
while (portList.hasMoreElements()) {
commPortId = Element();
// 判断是否是串⼝
if (PortType() == CommPortIdentifier.PORT_SERIAL) {
// ⽐较串⼝名称是否是指定串⼝
if (SerialNumber().Name())) {
// 串⼝存在
isExsist = true;
// 打开串⼝
try {
// open:(应⽤程序名【随意命名】,阻塞时等待的毫秒数)
serialPort = (SerialPort) commPortId.open(SimpleName(), 2000);
// 设置串⼝监听
serialPort.addEventListener(this);
/
/ 设置串⼝数据时间有效(可监听)
// 设置串⼝通讯参数:波特率,数据位,停⽌位,校验⽅式
serialPort.BaudRate(), DataBit(),                                StopBit(), CheckoutBit());
} catch (PortInUseException e) {
throw new CustomException("端⼝被占⽤");
} catch (TooManyListenersException e) {
throw new CustomException("过多");
} catch (UnsupportedCommOperationException e) {
throw new CustomException("不⽀持的COMM端⼝操作异常");
}
// 结束循环
break;
}
}
}
// 若不存在该串⼝则抛出异常
if (!isExsist) {
throw new CustomException("不存在该串⼝!");
}
}
/**
* 实现接⼝SerialPortEventListener中的⽅法读取从串⼝中接收的数据
*/
@Override
public void serialEvent(SerialPortEvent event) {
switch (EventType()) {
case SerialPortEvent.BI: // 通讯中断
case SerialPortEvent.OE: // 溢位错误
case SerialPortEvent.FE: // 帧错误
case SerialPortEvent.PE: // 奇偶校验错误
case SerialPortEvent.CD: // 载波检测
case SerialPortEvent.CTS: // 清除发送
case SerialPortEvent.DSR: // 数据设备准备好
case SerialPortEvent.RI: // 响铃侦测
case SerialPortEvent.OUTPUT_BUFFER_EMPTY: // 输出缓冲区已清空
break;
case SerialPortEvent.DATA_AVAILABLE: // 有数据到达
// 调⽤读取数据的⽅法
readComm();
break;
default:
break;
}
}
/**
* 读取串⼝返回信息
* @author LinWenLi
* @date 2018年7⽉21⽇下午3:43:04
* @return: void
*/
public void readComm() {
try {
inputStream = InputStream();
// 通过输⼊流对象的available⽅法获取数组字节长度
byte[] readBuffer = new byte[inputStream.available()];
// 从线路上读取数据流
int len = 0;
while ((len = ad(readBuffer)) != -1) {         // 直接获取到的数据                data = new String(readBuffer, 0, len).trim();         // 转为⼗六进制数据
dataHex = bytesToHexString(readBuffer);
System.out.println("data:" + data);
System.out.println("dataHex:" + dataHex);// 读取后置空流对象
inputStream.close();
inputStream = null;
break;
}
} catch (IOException e) {
throw new CustomException("读取串⼝数据时发⽣IO异常");
}
}
/**
* 发送信息到串⼝
* @author LinWenLi
* @date 2018年7⽉21⽇下午3:45:22
* @param: data
* @return: void
* @throws
*/
public void sendComm(String data) {
byte[] writerBuffer = null;
try {
writerBuffer = hexToByteArray(data);
} catch (NumberFormatException e) {
throw new CustomException("命令格式错误!");
}
try {
outputStream = OutputStream();
outputStream.write(writerBuffer);
outputStream.flush();
} catch (NullPointerException e) {
throw new CustomException("不到串⼝。");
} catch (IOException e) {
throw new CustomException("发送信息到串⼝时发⽣IO异常");
}
}
/**
* 关闭串⼝
* @author LinWenLi
* @date 2018年7⽉21⽇下午3:45:43
* @Description: 关闭串⼝
* @param:
* @return: void
* @throws
*/
public void closeSerialPort() {
if (serialPort != null) {
if (inputStream != null) {
java64位try {
inputStream.close();
inputStream = null;
} catch (IOException e) {
throw new CustomException("关闭输⼊流时发⽣IO异常");
}
}
if (outputStream != null) {
try {
outputStream.close();
outputStream = null;
} catch (IOException e) {
throw new CustomException("关闭输出流时发⽣IO异常");
}
}
serialPort.close();
serialPort = null;
}
}
/**
* ⼗六进制串⼝返回值获取
*/
public String getDataHex() {
String result = dataHex;
// 置空执⾏结果
dataHex = null;
// 返回执⾏结果
return result;
}
/**
* 串⼝返回值获取
*/
public String getData() {
String result = data;
/
/ 置空执⾏结果
data = null;
// 返回执⾏结果
return result;
}
/**
* Hex字符串转byte
* @param inHex 待转换的Hex字符串
* @return 转换后的byte
*/
public static byte hexToByte(String inHex) {
return (byte) Integer.parseInt(inHex, 16);
}
/**
* hex字符串转byte数组
* @param inHex 待转换的Hex字符串
* @return 转换后的byte数组结果
*/
public static byte[] hexToByteArray(String inHex) {
int hexlen = inHex.length();
byte[] result;
if (hexlen % 2 == 1) {
/
/ 奇数
hexlen++;
result = new byte[(hexlen / 2)];
inHex = "0" + inHex;
} else {
// 偶数
result = new byte[(hexlen / 2)];
}
int j = 0;
for (int i = 0; i < hexlen; i += 2) {
result[j] = hexToByte(inHex.substring(i, i + 2));
j++;
}
return result;
}
/**
* 数组转换成⼗六进制字符串
* @param byte[]
* @return HexString
*/
public static final String bytesToHexString(byte[] bArray) {
StringBuffer sb = new StringBuffer(bArray.length);
String sTemp;
for (int i = 0; i < bArray.length; i++) {
sTemp = HexString(0xFF & bArray[i]);
if (sTemp.length() < 2)
sb.append(0);
sb.UpperCase());
}
String();
}
}
调⽤串⼝操作类的代码:
public static void main(String[] args) {
// 实例化串⼝操作类对象
SerialPortUtils serialPort = new SerialPortUtils();
// 创建串⼝必要参数接收类并赋值,赋值串⼝号,波特率,校验位,数据位,停⽌位
ParamConfig paramConfig = new ParamConfig("COM4", 9600, 0, 8, 1);
// 初始化设置,打开串⼝,开始监听读取串⼝数据
serialPort.init(paramConfig);
// 调⽤串⼝操作类的sendComm⽅法发送数据到串⼝
serialPort.sendComm("FEF10A000000000000000AFF");
// 关闭串⼝(注意:如果需要接收串⼝返回数据的,请不要执⾏这句,保持串⼝监听状态)
serialPort.closeSerialPort();
}
当执⾏main⽅法中的代码且未执⾏关闭串⼝时,程序将⼀直处于开启状态,⾃动监听,接收读取来⾃串⼝的数据。
注意:⼀个串⼝只能打开⼀次,并只⽀持⼀个程序调⽤。
以上所记录的是简单测试java是否能成功操作串⼝数据,⾄于本⼈所写的Web端的读卡器调试功能则是在串⼝操作类的基础上编写⽹页界⾯,通过请求来控制串⼝的开启关闭及相应的设置,功能⽐较简单,放个界⾯记录⼀下:
本篇⽂章就到这⾥了,希望能够给你带来帮助,也希望您能够多多关注的更多内容!