TestGetPortList.java php
package michael.comm.serial;
import java.util.Enumeration;
import javax.comm.CommDriver;
import javax.comm.CommPortIdentifier;
import javax.comm.SerialPort;
/**
* @author michael
*
*/
public class TestGetPortList {
/**淘寶女裝夏裝新款
* @param args
* @throws Exception
*/
public static void main(String[] args) throws Exception {
// 人工加載驅動
// MainTest.driverInit();
TestGetPortList.getCommPortList();
// 人工加載驅動獲取端口列表
// TestGetPortList.getPortByDriver();
}
/**
* 手工加載驅動<br>
* 正常狀況下程序會自動加載驅動,故一般不須要人工加載<br>
* 每重複加載一次,會把端口重複註冊,CommPortIdentifier.getPortIdentifiers()獲取的端口就會重複
*/
public static void driverManualInit() {
String driverName = "com.sun.comm.Win32Driver";
String libname = "win32com";
CommDriver commDriver = null;
try {
System.loadLibrary("win32com");
System.out.println(libname + " Library Loaded");
commDriver = (javax.comm.CommDriver) Class.forName(driverName)
.newInstance();
commDriver.initialize();
System.out.println("comm Driver Initialized");
} catch (Exception e) {
System.err.println(e);
}
}
/**
* 獲取端口列表
*/
public static void getCommPortList() {
CommPortIdentifier portId;
Enumeration portEnum = CommPortIdentifier.getPortIdentifiers();
while (portEnum.hasMoreElements()) {
portId = (CommPortIdentifier) portEnum.nextElement();
if (portId.getPortType() == CommPortIdentifier.PORT_SERIAL) {
System.out.println("串口: name-" + portId.getName()
+ " 是否佔用-" + portId.isCurrentlyOwned());
} else {
System.out.println("並口: name-" + portId.getName()
+ " 是否佔用-" + portId.isCurrentlyOwned());
}
}
System.out.println("-------------------------------------");
}
/**
*
*/
public static void getPortByDriver() {
String driverName = "com.sun.comm.Win32Driver";
String libname = "win32com";
CommDriver commDriver = null;
try {
System.loadLibrary("win32com");
System.out.println(libname + " Library Loaded");
commDriver = (CommDriver) Class.forName(driverName).newInstance();
commDriver.initialize();
System.out.println("comm Driver Initialized");
} catch (Exception e) {
System.err.println(e);
}
SerialPort sPort = null;
try {
sPort = (SerialPort) commDriver.getCommPort("COM24",
CommPortIdentifier.PORT_SERIAL);
System.out.println("find CommPort:" + sPort.toString());
} catch (Exception e) {
System.out.println(e.getMessage());
}
}
}html