操作注册表编辑器

1、注册表

首先用【win+r】打开运行窗口,然后执行【regedit】打开注册表编辑器。
在这里插入图片描述
点击确定即会出现如下图所示的注册表编辑器:
在这里插入图片描述

2、cmd操作注册表

  • 查询注册表
    通过cmd终端窗口可查询出reg query的用法如下:
C:\Users\Administrator>reg query /?
 
REG QUERY KeyName [/v [ValueName] | /ve] [/s]
          [/f Data [/k] [/d] [/c] [/e]] [/t Type] [/z] [/se Separator]
          [/reg:32 | /reg:64]
 
  KeyName  [\\Machine\]FullKey
           Machine - 远程机器名称,省略当前机器的默认值。在远程机器上
                     只有 HKLMHKU 可用。
           FullKey -ROOTKEY\SubKey 名称形式
                ROOTKEY - [ HKLM | HKCU | HKCR | HKU | HKCC ]
                SubKey  - 在选择的 ROOTKEY 下的注册表项的全名
 
  /v       具体的注册表项值的查询。
           如果省略,会查询该项的所有值。
 
           只有与 /f 开关一起指定的情况下,此开关的参数才是可选的。它指定
           只在值名称中搜索。
 
  /ve      查询默认值或空值名称(默认)/s       循环查询所有子项和值(如 dir /s)/se      为 REG_MULTI_SZ 在数据字符串中指定分隔符(长度只为 1 个字符)。
           默认分隔符为 "\0"/f       指定搜索的数据或模式。
           如果字符串包含空格,请使用双引号。默认为 "*"/k       指定只在项名称中搜索。
 
  /d       指定只在数据中搜索。
 
  /c       指定搜索时区分大小写。
           默认搜索为不区分大小写。
 
  /e       指定只返回完全匹配。
           默认是返回所有匹配。
 
  /t       指定注册表值数据类型。
           有效的类型是:
             REG_SZ, REG_MULTI_SZ, REG_EXPAND_SZ,
             REG_DWORD, REG_QWORD, REG_BINARY, REG_NONE
           默认为所有类型。
 
  /z       详细: 显示值名称类型的数字等值。
 
 /reg:32  指定应该使用 32 位注册表视图访问的注册表项。
 
 /reg:64  指定应该使用 64 位注册表视图访问的注册表项。
 
示例:
 
  REG QUERY HKLM\Software\Microsoft\ResKit /v Version
    显示注册表值 Version 的值
 
  REG QUERY \\ABC\HKLM\Software\Microsoft\ResKit\Nt\Setup /s
    显示远程机器 ABC 上的、在注册表项设置下的所有子项和值
 
  REG QUERY HKLM\Software\Microsoft\ResKit\Nt\Setup /se #
    用 "#" 作为分隔符,显示类型为 REG_MULTI_SZ 的所有值名称的所有
    子项和值。
 
  REG QUERY HKLM /f SYSTEM /t REG_SZ /c /e
    以区分大小写的形式显示项、值和数据和数据类型 REG_SZ
    的、在 HKLM 更目录下的、"SYSTEM" 出现的精确次数
 
  REG QUERY HKCU /f 0F /d /t REG_BINARY
    显示在 HKCU 根目录下、数据类型为 REG_BINARY 的数据的项、值和
    数据的 "0F" 出现的次数。
 
  REG QUERY HKLM\SOFTWARE /ve
    显示在 HKLM\SOFTWARE 下的项、值和数据(默认)

在这里插入图片描述

  • 添加注册表
    通过cmd终端窗口可查询出reg add的用法如下:
C:\Users\Administrator>reg add /?
 
REG ADD KeyName [/v ValueName | /ve] [/t Type] [/s Separator] [/d Data] [/f]
        [/reg:32 | /reg:64]
 
  KeyName  [\\Machine\]FullKey
           Machine  远程机器名 - 忽略默认到当前机器。远程机器上
                    只有 HKLMHKU 可用。
           FullKey  ROOTKEY\SubKey
           ROOTKEY  [ HKLM | HKCU | HKCR | HKU | HKCC ]
           SubKey   所选 ROOTKEY 下注册表项的完整名称。
 
  /v       所选项之下要添加的值名称。
 
  /ve      为注册表项添加空白值名称(默认)/t       RegKey 数据类型
           [ REG_SZ    | REG_MULTI_SZ | REG_EXPAND_SZ |
             REG_DWORD | REG_QWORD    | REG_BINARY    | REG_NONE ]
           如果忽略,则采用 REG_SZ/s       指定一个在 REG_MULTI_SZ 数据字符串中用作分隔符的字符
           如果忽略,则将 "\0" 用作分隔符。
 
  /d       要分配给添加的注册表 ValueName 的数据。
 
  /f       不用提示就强行覆盖现有注册表项。
 
 /reg:32  指定应该使用 32 位注册表视图访问的注册表项。
 
 /reg:64  指定应该使用 64 位注册表视图访问的注册表项。
 
例如:
 
  REG ADD \\ABC\HKLM\Software\MyCo
    添加远程机器 ABC 上的一个注册表项 HKLM\Software\MyCo
 
  REG ADD HKLM\Software\MyCo /v Data /t REG_BINARY /d fe340ead
    添加一个值(名称: Data,类型: REG_BINARY,数据: fe340ead)
 
  REG ADD HKLM\Software\MyCo /v MRU /t REG_MULTI_SZ /d fax\0mail
    添加一个值(名称: MRU,类型: REG_MULTI_SZ,数据: fax\0mail\0\0)
 
  REG ADD HKLM\Software\MyCo /v Path /t REG_EXPAND_SZ /d ^%systemroot^%
    添加一个值(名称: Path,类型: REG_EXPAND_SZ,数据: %systemroot%)
    注意: 在扩充字符串中使用插入符号 ( ^ )
  • 删除注册表
    通过cmd终端窗口可查询出reg delete的用法如下:
C:\Users\Administrator>reg delete /?
 
REG DELETE KeyName [/v ValueName | /ve | /va] [/f] [/reg:32 | /reg:64]
 
  KeyName    [\\Machine\]FullKey
    远程机器名 - 如果省略,默认情况下将使用当前机器。
             远程机器上只有 HKLMHKU 可用。
    FullKey  ROOTKEY\SubKey
    ROOTKEY  [ HKLM | HKCU | HKCR | HKU | HKCC ]
    SubKey   所选 ROOTKEY 下面的注册表项的全名。
 
  ValueName  所选项下面的要删除的值名称。
             如果省略,则删除该项下面的所有子项和值。
 
  /ve        删除空值名称的值(默认)/va        删除该项下面的所有值。
 
  /f         不用提示,强制删除。
 
  /reg:32    指定应使用 32 位注册表视图访问
             注册表项。
 
  /reg:64    指定应使用 64 位注册表视图访问
             注册表项。
 
示例:
 
  REG DELETE HKLM\Software\MyCo\MyApp\Timeout
    删除注册表项 Timeout 及其所有子项和值
 
  REG DELETE \\ZODIAC\HKLM\Software\MyCo /v MTU
    删除 ZODIAC 上的 MyCo 下面的注册表值 MTU
  • 修改注册表
    修改注册表的命令即为添加注册表的命令,reg add 即为如果添加的key不存在则创建,存在则修改key对应的值。
    看到网上有些说是reg modify命令修改注册表,但在cmd上查询并没有此命令:
    在这里插入图片描述

3、Java操作注册表

  • 方法一:
    创建Process 对象用Runtime.getRuntime().exec()调用终端窗口cmd执行相应bat命令。
	public static void changeStart(boolean isStartAtLogon) throws IOException{  
      String regKey = "HKEY_CURRENT_USER\\SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run";  
      String myAppName = "mgtest";  
      String exePath = "\"D:\\Program Files (x86)\\love\\HelloWorld.exe\"";  
      Runtime.getRuntime().exec("reg "+(isStartAtLogon?"add ":"delete ")+regKey+" /v "+myAppName+(isStartAtLogon?" /t reg_sz /d "+exePath:" /f"));  
     }  
       
     public static void main(String[] args) throws IOException {  
           try {
            changeStart(true);
        } catch (IOException e) {
            //changeStart(false);
            e.printStackTrace();
        }
     }  
  • 方法二:
    运用操作注册表的工具类调用相关方法即可:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;
import java.util.ArrayList;
import java.util.List;
import java.util.StringTokenizer;
import java.util.prefs.Preferences;

/**
 * Windows下读取注册表的工具类
 *
 * 使用这些方法的示例如下:
 *
 * 下面的方法从给定路径检索键的值:
 *
 * String hex = WinRegistry.valueForKey(WinRegistry.HKEY_LOCAL_MACHINE, "SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\WindowsUpdate\\Auto Update", "AUOptions");
 *
 * 此方法检索指定路径的所有数据(以键和值的形式):
 *
 * Map<String, String> map = WinRegistry.valuesForPath(WinRegistry.HKEY_LOCAL_MACHINE, "SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\WSMAN");
 *
 * 此方法从给定路径递归检索键的值:
 *
 * String val = WinRegistry.valueForKeyPath(WinRegistry.HKEY_LOCAL_MACHINE, "System", "TypeID");
 *
 * 并且这个方法递归地从给定路径中检索一个键的所有值:
 *
 * List<String> list = WinRegistry.valuesForKeyPath( WinRegistry.HKEY_LOCAL_MACHINE, //HKEY "SOFTWARE\\Wow6432Node\\Microsoft\\Windows\\CurrentVersion\\Uninstall", //path "DisplayName" //Key );
 *
 * 在上面的代码中,我检索了Windows系统中所有已安装的软件名称。
 *
 * 注意:请参阅这些方法的文档。
 *
 * 这个检索给定路径的所有子键:
 *
 * List<String> list3 = WinRegistry.subKeysForPath(WinRegistry.HKEY_CURRENT_USER, "Software");
 *
 * 注意:在这个过程中,我只修改了阅读目的的方法,而不是像createKey、删除Key等写作目的的方法。它们仍然和我收到的一样。
 *
 * https://cloud.tencent.com/developer/ask/43600
 */
@SuppressWarnings("all")
public class WinRegistryUtils {

    private static final int REG_SUCCESS = 0;
    private static final int REG_NOTFOUND = 2;
    private static final int KEY_READ = 0x20019;
    private static final int REG_ACCESSDENIED = 5;
    private static final int KEY_ALL_ACCESS = 0xf003f;
    public static final int HKEY_CLASSES_ROOT = 0x80000000;
    public static final int HKEY_CURRENT_USER = 0x80000001;
    public static final int HKEY_LOCAL_MACHINE = 0x80000002;
    private static final String CLASSES_ROOT = "HKEY_CLASSES_ROOT";
    private static final String CURRENT_USER = "HKEY_CURRENT_USER";
    private static final String LOCAL_MACHINE = "HKEY_LOCAL_MACHINE";
    private static Preferences userRoot = Preferences.userRoot();
    private static Preferences systemRoot = Preferences.systemRoot();
    private static Class<? extends Preferences> userClass = userRoot.getClass();
    private static Method regOpenKey = null;
    private static Method regCloseKey = null;
    private static Method regQueryValueEx = null;
    private static Method regEnumValue = null;
    private static Method regQueryInfoKey = null;
    private static Method regEnumKeyEx = null;
    private static Method regCreateKeyEx = null;
    private static Method regSetValueEx = null;
    private static Method regDeleteKey = null;
    private static Method regDeleteValue = null;

    static {
        try {
            regOpenKey = userClass.getDeclaredMethod("WindowsRegOpenKey", new Class[] {int.class, byte[].class, int.class});
            regOpenKey.setAccessible(true);
            regCloseKey = userClass.getDeclaredMethod("WindowsRegCloseKey", new Class[] {int.class});
            regCloseKey.setAccessible(true);
            regQueryValueEx = userClass.getDeclaredMethod("WindowsRegQueryValueEx", new Class[] {int.class, byte[].class});
            regQueryValueEx.setAccessible(true);
            regEnumValue = userClass.getDeclaredMethod("WindowsRegEnumValue", new Class[] {int.class, int.class, int.class});
            regEnumValue.setAccessible(true);
            regQueryInfoKey = userClass.getDeclaredMethod("WindowsRegQueryInfoKey1", new Class[] {int.class});
            regQueryInfoKey.setAccessible(true);
            regEnumKeyEx = userClass.getDeclaredMethod("WindowsRegEnumKeyEx", new Class[] {int.class, int.class, int.class});
            regEnumKeyEx.setAccessible(true);
            regCreateKeyEx = userClass.getDeclaredMethod("WindowsRegCreateKeyEx", new Class[] {int.class, byte[].class});
            regCreateKeyEx.setAccessible(true);
            regSetValueEx = userClass.getDeclaredMethod("WindowsRegSetValueEx", new Class[] {int.class, byte[].class, byte[].class});
            regSetValueEx.setAccessible(true);
            regDeleteValue = userClass.getDeclaredMethod("WindowsRegDeleteValue", new Class[] {int.class, byte[].class});
            regDeleteValue.setAccessible(true);
            regDeleteKey = userClass.getDeclaredMethod("WindowsRegDeleteKey", new Class[] {int.class, byte[].class});
            regDeleteKey.setAccessible(true);
        }
        catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * Reads value for the key from given path
     * @param hkey   HKEY_CURRENT_USER/HKEY_LOCAL_MACHINE
     * @param path
     * @param key
     * @return the value
     * @throws IllegalArgumentException
     * @throws IllegalAccessException
     * @throws InvocationTargetException
     * @throws IOException
     */
    public static String valueForKey(int hkey, String path, String key)
            throws IllegalArgumentException, IllegalAccessException, InvocationTargetException, IOException {
        if (hkey == HKEY_LOCAL_MACHINE)
            return valueForKey(systemRoot, hkey, path, key);
        else if (hkey == HKEY_CURRENT_USER)
            return valueForKey(userRoot, hkey, path, key);
        else
            return valueForKey(null, hkey, path, key);
    }

    /**
     * Reads all key(s) and value(s) from given path
     * @param hkey  HKEY_CURRENT_USER/HKEY_LOCAL_MACHINE
     * @param path
     * @return the map of key(s) and corresponding value(s)
     * @throws IllegalArgumentException
     * @throws IllegalAccessException
     * @throws InvocationTargetException
     * @throws IOException
     */
    public static Map<String, String> valuesForPath(int hkey, String path)
            throws IllegalArgumentException, IllegalAccessException, InvocationTargetException, IOException {
        if (hkey == HKEY_LOCAL_MACHINE)
            return valuesForPath(systemRoot, hkey, path);
        else if (hkey == HKEY_CURRENT_USER)
            return valuesForPath(userRoot, hkey, path);
        else
            return valuesForPath(null, hkey, path);
    }

    /**
     * Read all the subkey(s) from a given path
     * @param hkey  HKEY_CURRENT_USER/HKEY_LOCAL_MACHINE
     * @param path
     * @return the subkey(s) list
     * @throws IllegalArgumentException
     * @throws IllegalAccessException
     * @throws InvocationTargetException
     */
    public static List<String> subKeysForPath(int hkey, String path)
            throws IllegalArgumentException, IllegalAccessException, InvocationTargetException {
        if (hkey == HKEY_LOCAL_MACHINE)
            return subKeysForPath(systemRoot, hkey, path);
        else if (hkey == HKEY_CURRENT_USER)
            return subKeysForPath(userRoot, hkey, path);
        else
            return subKeysForPath(null, hkey, path);
    }

    /**
     * Create a key
     * @param hkey  HKEY_CURRENT_USER/HKEY_LOCAL_MACHINE
     * @param key
     * @throws IllegalArgumentException
     * @throws IllegalAccessException
     * @throws InvocationTargetException
     */
    public static void createKey(int hkey, String key)
            throws IllegalArgumentException, IllegalAccessException, InvocationTargetException {
        int [] ret;
        if (hkey == HKEY_LOCAL_MACHINE) {
            ret = createKey(systemRoot, hkey, key);
            regCloseKey.invoke(systemRoot, new Object[] { new Integer(ret[0]) });
        } else if (hkey == HKEY_CURRENT_USER) {
            ret = createKey(userRoot, hkey, key);
            regCloseKey.invoke(userRoot, new Object[] { new Integer(ret[0]) });
        } else
            throw new IllegalArgumentException("hkey=" + hkey);
        if (ret[1] != REG_SUCCESS)
            throw new IllegalArgumentException("rc=" + ret[1] + "  key=" + key);
    }

    /**
     * Write a value in a given key/value name
     * @param hkey
     * @param key
     * @param valueName
     * @param value
     * @throws IllegalArgumentException
     * @throws IllegalAccessException
     * @throws InvocationTargetException
     */
    public static void writeStringValue(int hkey, String key, String valueName, String value)
            throws IllegalArgumentException, IllegalAccessException, InvocationTargetException {
        if (hkey == HKEY_LOCAL_MACHINE)
            writeStringValue(systemRoot, hkey, key, valueName, value);
        else if (hkey == HKEY_CURRENT_USER)
            writeStringValue(userRoot, hkey, key, valueName, value);
        else
            throw new IllegalArgumentException("hkey=" + hkey);
    }

    /**
     * Delete a given key
     * @param hkey
     * @param key
     * @throws IllegalArgumentException
     * @throws IllegalAccessException
     * @throws InvocationTargetException
     */
    public static void deleteKey(int hkey, String key)
            throws IllegalArgumentException, IllegalAccessException, InvocationTargetException {
        int rc = -1;
        if (hkey == HKEY_LOCAL_MACHINE)
            rc = deleteKey(systemRoot, hkey, key);
        else if (hkey == HKEY_CURRENT_USER)
            rc = deleteKey(userRoot, hkey, key);
        if (rc != REG_SUCCESS)
            throw new IllegalArgumentException("rc=" + rc + "  key=" + key);
    }

    /**
     * delete a value from a given key/value name
     * @param hkey
     * @param key
     * @param value
     * @throws IllegalArgumentException
     * @throws IllegalAccessException
     * @throws InvocationTargetException
     */
    public static void deleteValue(int hkey, String key, String value)
            throws IllegalArgumentException, IllegalAccessException, InvocationTargetException {
        int rc = -1;
        if (hkey == HKEY_LOCAL_MACHINE)
            rc = deleteValue(systemRoot, hkey, key, value);
        else if (hkey == HKEY_CURRENT_USER)
            rc = deleteValue(userRoot, hkey, key, value);
        if (rc != REG_SUCCESS)
            throw new IllegalArgumentException("rc=" + rc + "  key=" + key + "  value=" + value);
    }

    // =====================

    private static int deleteValue(Preferences root, int hkey, String key, String value)
            throws IllegalArgumentException, IllegalAccessException, InvocationTargetException {
        int[] handles = (int[]) regOpenKey.invoke(root, new Object[] {new Integer(hkey), toCstr(key), new Integer(KEY_ALL_ACCESS)});
        if (handles[1] != REG_SUCCESS)
            return handles[1];                                  // can be REG_NOTFOUND, REG_ACCESSDENIED
        int rc =((Integer) regDeleteValue.invoke(root, new Object[] {new Integer(handles[0]), toCstr(value)})).intValue();
        regCloseKey.invoke(root, new Object[] { new Integer(handles[0])});
        return rc;
    }

    private static int deleteKey(Preferences root, int hkey, String key)
            throws IllegalArgumentException, IllegalAccessException, InvocationTargetException {
        int rc =((Integer) regDeleteKey.invoke(root, new Object[] {new Integer(hkey), toCstr(key)})).intValue();
        return rc;                                                  // can REG_NOTFOUND, REG_ACCESSDENIED, REG_SUCCESS
    }

    private static String valueForKey(Preferences root, int hkey, String path, String key)
            throws IllegalArgumentException, IllegalAccessException, InvocationTargetException, IOException {
        int[] handles = (int[]) regOpenKey.invoke(root, new Object[] {new Integer(hkey), toCstr(path), new Integer(KEY_READ)});
        if (handles[1] != REG_SUCCESS)
            throw new IllegalArgumentException("The system can not find the specified path: '"+getParentKey(hkey)+"\\"+path+"'");
        byte[] valb = (byte[]) regQueryValueEx.invoke(root, new Object[] {new Integer(handles[0]), toCstr(key)});
        regCloseKey.invoke(root, new Object[] {new Integer(handles[0])});
        return (valb != null ? parseValue(valb) : queryValueForKey(hkey, path, key));
    }

    private static String queryValueForKey(int hkey, String path, String key) throws IOException {
        return queryValuesForPath(hkey, path).get(key);
    }

    private static Map<String,String> valuesForPath(Preferences root, int hkey, String path)
            throws IllegalArgumentException, IllegalAccessException, InvocationTargetException, IOException {
        HashMap<String, String> results = new HashMap<String,String>();
        int[] handles = (int[]) regOpenKey.invoke(root, new Object[] {new Integer(hkey), toCstr(path), new Integer(KEY_READ)});
        if (handles[1] != REG_SUCCESS)
            throw new IllegalArgumentException("The system can not find the specified path: '"+getParentKey(hkey)+"\\"+path+"'");
        int[] info = (int[]) regQueryInfoKey.invoke(root, new Object[] {new Integer(handles[0])});
        int count = info[2];                            // Fixed: info[0] was being used here
        int maxlen = info[4];                           // while info[3] was being used here, causing wrong results
        for(int index=0; index<count; index++) {
            byte[] valb = (byte[]) regEnumValue.invoke(root, new Object[] {new Integer(handles[0]), new Integer(index), new Integer(maxlen + 1)});
            String vald = parseValue(valb);
            if(valb == null || vald.isEmpty())
                return queryValuesForPath(hkey, path);
            results.put(vald, valueForKey(root, hkey, path, vald));
        }
        regCloseKey.invoke(root, new Object[] {new Integer(handles[0])});
        return results;
    }

    /**
     * Searches recursively into the path to find the value for key. This method gives
     * only first occurrence value of the key. If required to get all values in the path
     * recursively for this key, then {@link #valuesForKeyPath(int hkey, String path, String key)}
     * should be used.
     * @param hkey
     * @param path
     * @param key
     * @param list
     * @return the value of given key obtained recursively
     * @throws IllegalArgumentException
     * @throws IllegalAccessException
     * @throws InvocationTargetException
     * @throws IOException
     */
    public static String valueForKeyPath(int hkey, String path, String key)
            throws IllegalArgumentException, IllegalAccessException, InvocationTargetException, IOException {
        String val;
        try {
            val = valuesForKeyPath(hkey, path, key).get(0);
        } catch(IndexOutOfBoundsException e) {
            throw new IllegalArgumentException("The system can not find the key: '"+key+"' after "
                    + "searching the specified path: '"+getParentKey(hkey)+"\\"+path+"'");
        }
        return val;
    }

    /**
     * Searches recursively into given path for particular key and stores obtained value in list
     * @param hkey
     * @param path
     * @param key
     * @param list
     * @return list containing values for given key obtained recursively
     * @throws IllegalArgumentException
     * @throws IllegalAccessException
     * @throws InvocationTargetException
     * @throws IOException
     */
    public static List<String> valuesForKeyPath(int hkey, String path, String key)
            throws IllegalArgumentException, IllegalAccessException, InvocationTargetException, IOException {
        List<String> list = new ArrayList<String>();
        if (hkey == HKEY_LOCAL_MACHINE)
            return valuesForKeyPath(systemRoot, hkey, path, key, list);
        else if (hkey == HKEY_CURRENT_USER)
            return valuesForKeyPath(userRoot, hkey, path, key, list);
        else
            return valuesForKeyPath(null, hkey, path, key, list);
    }

    private static List<String> valuesForKeyPath(Preferences root, int hkey, String path, String key, List<String> list)
            throws IllegalArgumentException, IllegalAccessException, InvocationTargetException, IOException {
        if(!isDirectory(root, hkey, path)) {
            takeValueInListForKey(hkey, path, key, list);
        } else {
            List<String> subKeys = subKeysForPath(root, hkey, path);
            for(String subkey: subKeys) {
                String newPath = path+"\\"+subkey;
                if(isDirectory(root, hkey, newPath))
                    valuesForKeyPath(root, hkey, newPath, key, list);
                takeValueInListForKey(hkey, newPath, key, list);
            }
        }
        return list;
    }

    /**
     * Takes value for key in list
     * @param hkey
     * @param path
     * @param key
     * @param list
     * @throws IllegalArgumentException
     * @throws IllegalAccessException
     * @throws InvocationTargetException
     * @throws IOException
     */
    private static void takeValueInListForKey(int hkey, String path, String key, List<String> list)
            throws IllegalArgumentException, IllegalAccessException, InvocationTargetException, IOException {
        String value = valueForKey(hkey, path, key);
        if(value != null)
            list.add(value);
    }

    /**
     * Checks if the path has more subkeys or not
     * @param root
     * @param hkey
     * @param path
     * @return true if path has subkeys otherwise false
     * @throws IllegalArgumentException
     * @throws IllegalAccessException
     * @throws InvocationTargetException
     */
    private static boolean isDirectory(Preferences root, int hkey, String path)
            throws IllegalArgumentException, IllegalAccessException, InvocationTargetException {
        return !subKeysForPath(root, hkey, path).isEmpty();
    }

    private static List<String> subKeysForPath(Preferences root, int hkey, String path)
            throws IllegalArgumentException, IllegalAccessException, InvocationTargetException {
        List<String> results = new ArrayList<String>();
        int[] handles = (int[]) regOpenKey.invoke(root, new Object[] {new Integer(hkey), toCstr(path), new Integer(KEY_READ)});
        if (handles[1] != REG_SUCCESS)
            throw new IllegalArgumentException("The system can not find the specified path: '"+getParentKey(hkey)+"\\"+path+"'");
        int[] info = (int[]) regQueryInfoKey.invoke(root, new Object[] {new Integer(handles[0])});
        int count  = info[0]; // Fix: info[2] was being used here with wrong results. Suggested by davenpcj, confirmed by Petrucio
        int maxlen = info[3]; // value length max
        for(int index=0; index<count; index++) {
            byte[] valb = (byte[]) regEnumKeyEx.invoke(root, new Object[] {new Integer(handles[0]), new Integer(index), new Integer(maxlen + 1)});
            results.add(parseValue(valb));
        }
        regCloseKey.invoke(root, new Object[] {new Integer(handles[0])});
        return results;
    }

    private static int [] createKey(Preferences root, int hkey, String key)
            throws IllegalArgumentException, IllegalAccessException, InvocationTargetException {
        return (int[]) regCreateKeyEx.invoke(root, new Object[] {new Integer(hkey), toCstr(key)});
    }

    private static void writeStringValue(Preferences root, int hkey, String key, String valueName, String value)
            throws IllegalArgumentException, IllegalAccessException, InvocationTargetException {
        int[] handles = (int[]) regOpenKey.invoke(root, new Object[] {new Integer(hkey), toCstr(key), new Integer(KEY_ALL_ACCESS)});
        regSetValueEx.invoke(root, new Object[] {new Integer(handles[0]), toCstr(valueName), toCstr(value)});
        regCloseKey.invoke(root, new Object[] {new Integer(handles[0])});
    }

    /**
     * Makes cmd query for the given hkey and path then executes the query
     * @param hkey
     * @param path
     * @return the map containing all results in form of key(s) and value(s) obtained by executing query
     * @throws IOException
     */
    private static Map<String, String> queryValuesForPath(int hkey, String path) throws IOException {
        String line;
        StringBuilder builder = new StringBuilder();
        Map<String, String> map = new HashMap<String, String>();
        Process process = Runtime.getRuntime().exec("reg query \""+getParentKey(hkey)+"\\" + path + "\"");
        BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
        while((line = reader.readLine()) != null) {
            if(!line.contains("REG_"))
                continue;
            StringTokenizer tokenizer = new StringTokenizer(line, " \t");
            while(tokenizer.hasMoreTokens()) {
                String token = tokenizer.nextToken();
                if(token.startsWith("REG_"))
                    builder.append("\t ");
                else
                    builder.append(token).append(" ");
            }
            String[] arr = builder.toString().split("\t");
            map.put(arr[0].trim(), arr[1].trim());
            builder.setLength(0);
        }
        return map;
    }

    /**
     * Determines the string equivalent of hkey
     * @param hkey
     * @return string equivalent of hkey
     */
    private static String getParentKey(int hkey) {
        if(hkey == HKEY_CLASSES_ROOT)
            return CLASSES_ROOT;
        else if(hkey == HKEY_CURRENT_USER)
            return CURRENT_USER;
        else if(hkey == HKEY_LOCAL_MACHINE)
            return LOCAL_MACHINE;
        return null;
    }

    /**
     *Intern method which adds the trailing \0 for the handle with java.dll
     * @param str String
     * @return byte[]
     */
    private static byte[] toCstr(String str) {
        if(str == null)
            str = "";
        return (str += "\0").getBytes();
    }

    /**
     * Method removes the trailing \0 which is returned from the java.dll (just if the last sign is a \0)
     * @param buf the byte[] buffer which every read method returns
     * @return String a parsed string without the trailing \0
     */
    private static String parseValue(byte buf[]) {
        if(buf == null)
            return null;
        String ret = new String(buf);
        if(ret.charAt(ret.length()-1) == '\0')
            return ret.substring(0, ret.length()-1);
        return ret;
    }
    
}


该工具类是网上找到的,目前只验证了valuesForPath可以获取到指定注册表下的所有键值或指定键的值,但修改和创建试了好像不起作用,调用createKey无效果,验证中发现是权限问题,由于代码运行默认以当前用户执行,则如果当前用户没有修改该注册表的权限则无法修改。
问题:不用Runtime.getRuntime().exec()该如何用Java对注册表进行修改?用Java调用Runtime.getRuntime().exec() 执行命令,该如何让其以system管理权限执行,且无需知道管理员的密码,也不需用户手动输入密码?

    public static void main(String[] args) {

        String regPath = "SYSTEM\\ControlSet001\\Control\\Class\\{4d36e972-e325-11ce-bfc1-08002be10318}";

        try {
            // 此方法检索指定路径的所有数据(以键和值的形式):
            Map<String, String> map = WinRegistryUtils.valuesForPath(WinRegistryUtils.HKEY_LOCAL_MACHINE, regPath);
            System.out.println(map);

            // 这个检索给定路径的所有子键:路径下的目录(子节点)
            List<String> list = WinRegistryUtils.subKeysForPath(WinRegistryUtils.HKEY_LOCAL_MACHINE, regPath);
            System.out.println(list);

            // WinRegistryUtils.createKey(WinRegistryUtils.HKEY_LOCAL_MACHINE, regPath);


        } catch (IOException | InvocationTargetException | IllegalAccessException exception) {
            exception.printStackTrace();
        }

    }

在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

4、开机自启动

根据搜索可知,开机自启动配置基本属于HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Run注册表下。有些在该注册表下的数据会在任务管理器下的启动下会存在,有些软件配置了开机自启动可能会影响其他的软件,这时就需要关闭它,一种是手动关闭,其次最好是代码实现自动检查,然后将其修改或关闭

@echo off
rem 注释:把exe增加到注册表中 regName 是注册名称,后一个是对应exe文件
rem reg add 注册表路径 /v 值名 /t 要修改的数值类型 /d 要输入的数据 /f(可根据情况自行添加,意为不用提示就强行改写现有注册表项)
reg add HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Run /v regName /t reg_sz /d "C:\study\qq.exe" -f

reg delete HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Run /v regName

for /f "usebackq tokens=1-3" %%a in (`reg query HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Run`) do (
    echo %%c | findstr %qq.exe% >null && (
        echo %%c 包含 qq.exe
        echo qq regName is : %%a
        rem 存在则将其从注册表中删除
        reg delete HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Run /v %%a /f
    )
)

// bat查询开机自启动列表
wmic startup list full
wmic startup where "Caption Like '%qq% list full

5、网卡电源管理配置

网卡电源管理配置如下图所示,想修改电源管理是否允许计算机关闭此设备以节约电源关闭。根据搜索可知属于HKEY_LOCAL_MACHINE\SYSTEM\ControlSet001\Control\Class{4d36e972-e325-11ce-bfc1-08002be10318}注册表下的子项节点,
在这里插入图片描述
DriverDesc表示网卡名称。PnPCapabilities代表电源管理设置,数字0表示启用USB Root Hub的电源管理(有些电脑开启时的值是16或其他);数字24将阻止窗口关闭USB根集线器或让设备唤醒计算机休眠。 找到PnPCapabilities。如果找不到PnPCapabilities,请尝试创建一个。右键单击空白,在新项中选择DWORD(32位)值,并重命名为PnPCapabilities。
在这里插入图片描述
然后有说只需改网卡名称不包含有以下关键字的:[“WAN Miniport”, “Microsoft Kernel”, “VirtualBox”, “Hyper-V”, “Array Networks”]。
则,修改参数值命令:

reg add HKEY_LOCAL_MACHINE\SYSTEM\ControlSet001\Control\Class\{4d36e972-e325-11ce-bfc1-08002be10318}\0001 /v PnPCapabilities /t reg_dword /d 24 -f

其次,修改完参数值之后需要重启以下网卡,保证修改的参数有效:

查看网卡:
netsh interface show interface

关闭网卡命令:
netsh interface set interface "适配器名称" disabled
netsh interface set interface "适配器名称" admin=disabled

开启网卡命令:
netsh interface set interface "适配器名称" enabled
netsh interface set interface "适配器名称" admin=enable
  • 30
    点赞
  • 28
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值