📄 commportmanager.java
字号:
import java.util.*;
import javax.comm.*;
public class CommPortManager extends PortManager {
public static Enumeration getAllPorts() {
CommPortIdentifier portId;
Enumeration portEnum;
Vector ports = new Vector();
portEnum = CommPortIdentifier.getPortIdentifiers();
while (portEnum.hasMoreElements()) {
portId = (CommPortIdentifier) portEnum.nextElement();
if (portId.getPortType() == CommPortIdentifier.PORT_SERIAL)
{
ports.addElement (portId.getName());
}
}
//add bogus port
ports.addElement("COM5");
return ports.elements (); //return enumeration
}
//-------------------------------------
public static Enumeration getAvailablePorts() {
Vector portOpenList = new Vector();
CommPortIdentifier portId;
Enumeration enum = getAllPorts();
while (enum.hasMoreElements ()) {
String portName = (String)enum.nextElement () ;
try {
//try to get port ownership
portId = CommPortIdentifier.getPortIdentifier(portName);
//if successful, open the port
CommPort cp = portId.open("SimpleComm",100);
//report success
portOpenList.addElement(portName);
cp.close();
}
catch(NoSuchPortException e){}
catch(PortInUseException e){}
}
return portOpenList.elements ();
}
//-------------------------------------
public static CommPort openPort(String portName) {
CommPortIdentifier portId;
try {
//try to get port ownership
portId = CommPortIdentifier.getPortIdentifier(portName);
//if successful, open the port
CommPort cp = portId.open("SimpleComm",100);
//report success
return cp;
}
catch(NoSuchPortException e){
return null;}
catch(PortInUseException e){
return null;}
}
//-------------------------------------
public static CommPort openPort() {
CommPortIdentifier portId;
Enumeration enum = getAvailablePorts();
if (enum.hasMoreElements ()) {
String portName = (String)enum.nextElement ();
try {
portId = CommPortIdentifier.getPortIdentifier(portName);
CommPort cp = portId.open("SimpleComm",100);
//report success
return cp;
}
catch(NoSuchPortException e){return null;}
catch(PortInUseException e){return null;}
}
else
return null;
}
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -