I'm creating a code for listing the COM ports and after that I want to select one of them. The list I get is an array of strings, so that I have to make a casting for the setter method, but the casting is not working. Why?
thanks in advance
package tests;
import gnu.io.*;
import java.util.*; import java.io.InputStream;
public class connectnow_array implements Runnable, SerialPortEventListener {
static CommPortIdentifier portId;
static Enumeration portList;
InputStream inputStream;
SerialPort serialPort;
Thread readThread;
byte[] readBuffer;
public static String[] listSerialPorts() {
Enumeration ports = CommPortIdentifier.getPortIdentifiers();
ArrayList portList = new ArrayList();
String portArray[] = null;
while (ports.hasMoreElements()) {
CommPortIdentifier currPortId = (CommPortIdentifier) ports.nextElement();
if (currPortId.getPortType() == CommPortIdentifier.PORT_SERIAL) {
portList.add(currPortId.getName());
}
}
portArray = (String[]) portList.toArray(new String[0]);
System.out.println("portList=" + portList);
return portArray;
}
public static void main(String[] args) {
String[] lista_de_puertos=null;
connectnow_array main = new connectnow_array();
lista_de_puertos=main.listSerialPorts();
//System.out.println(Arrays.toString(lista_de_puertos));
System.out.println(lista_de_puertos[0]);
System.out.println(getPortId());
setPortId((CommPortIdentifier)lista_de_puertos[0]); //PROBLEM HERE**
}
public static CommPortIdentifier getPortId() {
return portId;
}
public static void setPortId(CommPortIdentifier portId) {
connectnow_array.portId = portId;
}
}
应该:
portArray = (String[]) portList.toArray(new String[portList.size()]);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.