public class SimpleRead implements SerialPortEventListener, Runnable {
static Enumeration portList;// 枚举类
static CommPortIdentifier portId;
SerialPort serialPort;
InputStream inputStream;
Thread readThread;
static boolean error = false;
// 串口事件
public void serialEvent(SerialPortEvent event) {
switch(event.getEventType()) {
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:
byte[] readBuffer = new byte[20];
try {
while (inputStream.available() > 0) {
int numBytes = inputStream.read(readBuffer);
}
System.out.print(new String(readBuffer));
} catch (IOException e) {}
break;
}
}
public void run() {
try {
Thread.sleep(20000);
} catch (InterruptedException e) {
System.out.println("线程出错");
}
}
public static void main(String[] args) {
portList = CommPortIdentifier.getPortIdentifiers();// 该对象又包含了系统中管理每个端口的CommPortIdentifier对象
// portList = CommPortIdentifier.getPortIdentifiers(CommPort);//用程序打开的端口相对应的CommPortIdentifier对象
try {
System.out.println(CommPortIdentifier.getPortIdentifier("COM4"));
} catch (NoSuchPortException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
while (portList.hasMoreElements()) {
portId = (CommPortIdentifier) portList.nextElement();
if (portId.getPortType() == CommPortIdentifier.PORT_SERIAL) {
if (portId.getName().equals("COM1")){
System.out.println("获得串口");
SimpleRead reader = new SimpleRead();
error = true;
}
}
}
if (!error) {
System.out.println("sorry!!!没有找到串口");
}
}
public SimpleRead() {
try {
serialPort = (SerialPort) portId.open("SimpleReadApp", 2000);// 第一个为应用程序名;第二个参数是在端口打开时阻塞等待的毫秒数
System.out.println("端口可正常使用");
} catch (PortInUseException e) {
System.out.println("端口正在使用中,等待两秒重试");
e.printStackTrace();
}
try {
inputStream = serialPort.getInputStream();
System.out.println("端口可输入数据");
} catch (IOException e) {
System.out.println("输入流对象出错");
e.printStackTrace();
}
try {
serialPort.addEventListener(this);
System.out.println("注册监听事件成功");
} catch (TooManyListenersException e) {
serialPort.notifyOnDataAvailable(true);
try {
serialPort.setSerialPortParams(9600, SerialPort.DATABITS_8,
SerialPort.STOPBITS_1, SerialPort.PARITY_NONE);
System.out.println("串口参数初始化成功");
} catch (UnsupportedCommOperationException e1) {
System.out.println("串口参数出错");
e1.printStackTrace();
}
readThread = new Thread(this);
readThread.start();
e.printStackTrace();
}
}
}
这个是我的代码,为什么一直提示找不到串口啊,我用超级终端连接的时候会提示有一个COM4,可是我把上面的参数也改成COM4也不行