以下代码的作用是读取USB设备:
package org.yangzc.reglistener;
import com.ice.jni.registry.Registry;
import com.ice.jni.registry.RegistryKey;
import com.ice.jni.registry.RegistryValue;
/**
* 操作注册表实例
* @author yangzc
*
*/
public class Domain1 {
private static final String REG_PATH = "SYSTEM\\CurrentControlSet\\Control\\DeviceClasses\\{53f56307-b6bf-11d0-94f2-00a0c91efb8b}";
private static final String REG_USBSTOR_Path = "SYSTEM\\CurrentControlSet\\Enum\\USB";
public static void main(String[] args) {
try {
RegistryKey child = Registry.HKEY_LOCAL_MACHINE.openSubKey(REG_PATH);
String curDeviceId = "";
for(int i=0; i< child.getNumberSubkeys(); i++){
try{
String key = child.regEnumKey(i);
RegistryKey devicekey = child.openSubKey(key, RegistryKey.ACCESS_READ);
RegistryKey ctrlkey =child.openSubKey(key, RegistryKey.ACCESS_READ).openSubKey("#\\Control", RegistryKey.ACCESS_READ);
RegistryValue value = ctrlkey.getValue("Linked");
if(value.getType() == RegistryValue.REG_DWORD){
String deviceInstance = devicekey.getStringValue("DeviceInstance");
String deviceInfo[] = deviceInstance.split("\\\\");
if(value.getByteData()[value.getByteLength()-1] == 1 && "".equals(curDeviceId)){
System.out.println("USB设备:" + deviceInfo[1] + "已经连接");
System.out.println("序列号:" + deviceInfo[2]);
RegistryKey usb = getUsbValue(deviceInfo[2].split("&")[0]);
if(usb != null){
System.out.println("设备描述:" + usb.getStringValue("DeviceDesc"));
System.out.println("硬件ID:" + usb.getStringValue("HardwareID"));
}
}
}
}catch(Exception e){
}
}
Thread.sleep(1000);
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* 返回USB设备
* @param serialNo
* @return
*/
private static RegistryKey getUsbValue(String serialNo){
try {
String subkey1 = null;
RegistryKey child = Registry.HKEY_LOCAL_MACHINE.openSubKey(REG_USBSTOR_Path);
for(int i=0; i< child.getNumberSubkeys(); i++){
String key = child.regEnumKey(i);
System.out.println(key);
RegistryKey devicekey = child.openSubKey(key, RegistryKey.ACCESS_READ);
int subKeys = devicekey.getNumberSubkeys();
for(int j=0; j< subKeys; j++){
String subkey = child.regEnumKey(j);
if(subkey.startsWith(serialNo)){
subkey1 = subkey;
}
}
return devicekey.openSubKey(subkey1, RegistryKey.ACCESS_READ);
}
} catch (Exception e) {
}
return null;
}
}
工程目录结构如下: