如何检查pc中的可用端口?

时间:2014-01-20 15:36:41

标签: java serial-port

我想要pc中的可用端口列表我在java中使用此代码但是获得响应 我导入javax.comm liabrary。请简短我的问题

由于

import java.util.Enumeration;

import javax.comm.CommPortIdentifier;


public class CommPortLister {

  /** Simple test program. */
  public static void main(String[] ap) {
    new CommPortLister().list();
  }

  /** Ask the Java Communications API * what ports it thinks it has. */
  protected void list() {
    // get list of ports available on this particular computer,
    // by calling static method in CommPortIdentifier.
    Enumeration pList = CommPortIdentifier.getPortIdentifiers();

    // Process the list.
    while (pList.hasMoreElements()) {
      CommPortIdentifier cpi = (CommPortIdentifier) pList.nextElement();
      System.out.print("Port " + cpi.getName() + " ");
      if (cpi.getPortType() == CommPortIdentifier.PORT_SERIAL) {
        System.out.println("is a Serial Port: " + cpi);
      } else if (cpi.getPortType() == CommPortIdentifier.PORT_PARALLEL) {
        System.out.println("is a Parallel Port: " + cpi);
      } else {
        System.out.println("is an Unknown Port: " + cpi);
      }
    }
  }
}

1 个答案:

答案 0 :(得分:1)

我一直在成功使用RXTX库来做同样的事情。使用RXTX的等效代码:

import gnu.io.*;
    static void listPorts()
    {
        java.util.Enumeration<CommPortIdentifier> portEnum = CommPortIdentifier.getPortIdentifiers();
        while ( portEnum.hasMoreElements() ) 
        {
            CommPortIdentifier portIdentifier = portEnum.nextElement();
            System.out.println(portIdentifier.getName()  +  " - " +  getPortTypeName(portIdentifier.getPortType()) );
        }        
    }

    static String getPortTypeName ( int portType )
    {
        switch ( portType )
        {
            case CommPortIdentifier.PORT_I2C:
                return "I2C";
            case CommPortIdentifier.PORT_PARALLEL:
                return "Parallel";
            case CommPortIdentifier.PORT_RAW:
                return "Raw";
            case CommPortIdentifier.PORT_RS485:
                return "RS485";
            case CommPortIdentifier.PORT_SERIAL:
                return "Serial";
            default:
                return "unknown type";
        }
}