简体   繁体   English

从字符串转换为CommPortIdentifier

[英]Casting from String to CommPortIdentifier

I'm creating a code for listing the COM ports and after that I want to select one of them. 我正在创建用于列出COM端口的代码,然后我要选择其中一个。 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. 我得到的列表是一个字符串数组,因此我必须对setter方法进行强制转换,但是强制转换无法正常工作。 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()]);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM