gpt4 book ai didi

java - 与串行端口通信时抛出异常

转载 作者:行者123 更新时间:2023-11-30 07:56:40 26 4
gpt4 key购买 nike

我正在尝试与串行端口通信。在下面的程序中,我列出了可用的端口,它给了我正确的输出,但是当我尝试与串行端口建立通信时,它给了我以下异常。

java.lang.ClassCastException: gnu.io.LPRPort cannot be cast to gnu.io.SerialPort

程序:

import gnu.io.CommPortIdentifier;
import gnu.io.*;
import java.io.*;
import java.util.Enumeration;

public class PortList {

private static CommPortIdentifier port;
private SerialPort serialport;
private InputStream inputstream;
private OutputStream outputstream;
private static Enumeration ports;

public static void main(String args[]) {
System.out.println("fdsgfjh");

ports = CommPortIdentifier.getPortIdentifiers();
System.out.println(ports.nextElement());
while (ports.hasMoreElements()) {
port = (CommPortIdentifier)ports.nextElement();
String type;
switch (port.getPortType()) {
case CommPortIdentifier.PORT_PARALLEL:
type = "Parallel";
break;
case CommPortIdentifier.PORT_SERIAL:
type = "Serial";
break;
default: /// Shouldn't happen
type = "Unknown";
break;
}
System.out.println(port.getName() + ": " + type);
}
PortList objOfClass=new PortList();
objOfClass.readData();

}

public void readData(){
try{
if (port.isCurrentlyOwned()) {
System.out.println("Port Is In Use");
}
else {
serialport=(SerialPort)port.open(this.getClass().getName(), 2000);//Giving Exception on this line.

System.out.println("Port Is Opened now");

int baudRate=serialport.getBaudRate();
System.out.println(Integer.toString(baudRate));

serialport.setSerialPortParams(1200, 8, 1, serialport.PARITY_NONE);
System.out.println("Properties are set");

inputstream=serialport.getInputStream();
outputstream=serialport.getOutputStream();

byte[] write={12,45,78};
outputstream.write(write);//you have to write the data in the byte format for that status is given in the byte.
outputstream.flush();

byte[] read=new byte[30];
inputstream.read(read);

for(int i =0; i< read.length;i++){
System.out.println(i+" "+read);
}
}
}
catch(Exception e){
e.printStackTrace();
}
}
}

感谢帮助。谢谢。

最佳答案

根据您的实现,port 将是最后列出的端口。最后列出的端口可能不是串行端口。在您的情况下,最后列出的端口似乎是并行端口。

关于java - 与串行端口通信时抛出异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32584729/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com