我是个新手,想用rxtxcomm读一个传感器通过USB传来的数据的,结果一直报错,搞了两天都没有解决。郁闷,求高手指导啊。
源码如下:
package com.comm;
import java.io.IOException;
import java.io.InputStream;
import gnu.io.CommPortIdentifier;
import gnu.io.NoSuchPortException;
import gnu.io.PortInUseException;
import gnu.io.SerialPort;
import gnu.io.UnsupportedCommOperationException;
public class ComPollingListener {
public static void main(String[] args) {
//1.定义变量
CommPortIdentifier com = null; //未打开的端口
SerialPort serialCom = null; //打开的端口
InputStream inputStream = null; //端口输入流
try {
//2.获取并打开串口COM
com=CommPortIdentifier.getPortIdentifier("COM3"); //com口为COM3
serialCom=(SerialPort) com.open("ComEventListener", 1000);
//设置端口参数
try {
serialCom.setSerialPortParams(
15200,//波特率
SerialPort.DATABITS_8,//数据位数
SerialPort.STOPBITS_1,//停止位
SerialPort.PARITY_NONE//奇偶位
);
}catch (UnsupportedCommOperationException e) {
e.printStackTrace();
}
//3.获取串口的输入流对象
inputStream = serialCom.getInputStream();
//4.从串口读入数据
//定义用于缓存读入数据的数组
byte[] cache = new byte[2];
//记录已经到达串口COM且未被读取的数据的字节(Byte)数。
int availableBytes = 0;
//无限循环,每隔20毫秒对串口COM进行一次扫描,检查是否有数据到达
while(true){
//获取串口COM收到的可用字节数
availableBytes = inputStream.available();
//如果可用字节数大于零则开始循环并获取数据
System.out.println(availableBytes+";");
while(availableBytes > 0){
//从串口的输入流对象中读入数据并将数据存放到缓存数组中
inputStream.read(cache);
// System.out.println("进来了");
System.out.println(cache.length);
//将获取到的数据进行转码并输出
for(int j = 0;j < cache.length && j < availableBytes; j++){
//因为COM口发送的是使用byte数组表示的字符串,所以在此将接收到的每个字节的数据都强制装换为char对象即可,
//这是一个简单的编码转换,可以根据需要进行更加复杂的编码转换
System.out.print((char)cache[j]);
// System.out.println(cache.length);
}
// System.out.println("完成");
//更新循环条件
availableBytes = inputStream.available();
}
//让线程睡眠20毫秒
Thread.sleep(20);
}
}catch (InterruptedException e){
e.printStackTrace();
}catch (NoSuchPortException e) {
//找不到串口的情况下抛出该异常
e.printStackTrace();
}catch (PortInUseException e) {
//如果因为端口被占用而导致打开失败,则抛出该异常
e.printStackTrace();
}catch (IOException e) {
//如果获取输出流失败,则抛出该异常
e.printStackTrace();
}
}
}
异常为:
A fatal error has been detected by the Java Runtime Environment:
#
EXCEPTION_ACCESS_VIOLATION (0xc0000005) at pc=0x0000000180005b00, pid=9664, tid=7652
#
JRE version: Java(TM) SE Runtime Environment (11.0.1+13) (build 11.0.1+13-LTS)
Java VM: Java HotSpot(TM) 64-Bit Server VM (11.0.1+13-LTS, mixed mode, tiered, compressed oops, g1 gc, windows-amd64)
Problematic frame:
C [rxtxSerial.dll+0x5b00]
#