Enumeration is empty when i am trying to populate it with com port list

467 views Asked by At

I have a device connected at my com port and I am trying to get its values but I am stuck at the first step.

I am unable to get the existing com ports. In the code below by enumeration seems to be empty because the program doesn't enter the while loop at all. Can anyone please help

public class connectnow implements Runnable, SerialPortEventListener {

    static CommPortIdentifier portId;
    static Enumeration portList;

    InputStream inputStream;
    SerialPort serialPort;
    Thread readThread;
    byte[] readBuffer;

    public static void main(String[] args) {

        portList = CommPortIdentifier.getPortIdentifiers();
        System.out.println("portList... " + portList);

        while (portList.hasMoreElements()) {
            System.out.println("yes");
        }
    }
1

There are 1 answers

0
Ziffusion On

This seems to work for me.

I had to install x64 version of RXTX from http://mfizz.com/oss/rxtx-for-java. The package is gnu.io (which is why you see the import). You may have to do something different.

Note that it takes a little while for getPortIdentifiers() to return. Give it time.

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

public class connectnow implements Runnable, SerialPortEventListener {

    static CommPortIdentifier portId;
    static Enumeration portList;

    InputStream inputStream;
    SerialPort serialPort;
    Thread readThread;
    byte[] readBuffer;

    public static void main(String[] args) {

        portList = CommPortIdentifier.getPortIdentifiers();
        System.out.println("portList=" + portList);

        while (portList.hasMoreElements()) {
            System.out.println("yes");
            CommPortIdentifier portId = (CommPortIdentifier)portList.nextElement();
            System.out.println("portId=" + portId);
        }
    }

    public void run() {
    }

    public void serialEvent(SerialPortEvent ev) {
    }
}