gpt4 book ai didi

java - 如何查看电脑可用端口?

转载 作者:行者123 更新时间:2023-12-01 13:36:22 25 4
gpt4 key购买 nike

我想要电脑中可用端口的列表我在java中使用此代码但没有得到响应我导入 javax.comm 库。请简述我的问题

谢谢

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);
}
}
}
}

最佳答案

我一直在使用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";
}
}

关于java - 如何查看电脑可用端口?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21238007/

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