java操作注册表实例代码

 

以下代码的作用是读取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;
	}
}

 

 

工程目录结构如下:

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值