JAVA获取USB信息
使用usb4java,在JAVA中获取设备的UBS信息
usb4java官网示例 (opens new window)
# 导入依赖
<dependency>
<groupId>org.usb4java</groupId>
<artifactId>usb4java-javax</artifactId>
<version>1.3.0</version>
</dependency>
# 配置
在资源目录下生成文件javax.usb.properties
并写入下面内容
javax.usb.services = org.usb4java.javax.Services
# 简单示例
@Slf4j
public class UsbUtil {
/**
* 查找指定 PID VID 设备
* @param vendorId VID
* @param productId PID
* @return 是否USB设备
*/
public static boolean findDevice(short vendorId, short productId) {
try {
UsbHub rootUsbHub = UsbHostManager.getUsbServices()
.getRootUsbHub();
UsbDevice device = findDevice(rootUsbHub, vendorId, productId);
return null != device;
} catch (UsbException e) {
log.error("USB检测异常",e);
return false;
}
}
/**
* 在一个Hub中查找指定 PID VID 设备
* @param vendorId VID
* @param productId PID
* @return 是否USB设备
*/
@SuppressWarnings("unchecked")
public static UsbDevice findDevice(UsbHub hub, short vendorId, short productId) {
for (UsbDevice device : (List<UsbDevice>) hub.getAttachedUsbDevices()) {
UsbDeviceDescriptor desc = device.getUsbDeviceDescriptor();
if (desc.idVendor() == vendorId && desc.idProduct() == productId) return device;
if (device.isUsbHub()) {
device = findDevice((UsbHub) device, vendorId, productId);
if (device != null) return device;
}
}
return null;
}
}
# 测试
上次更新: 2024/11/05, 08:29:31