`

Read/Write the Registry (Windows)

阅读更多
his technique was first seen in this post.

package com.rgagnon.howto;

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.prefs.Preferences;

public class WinRegistry {
  // inspired by
  // http://javabyexample.wisdomplug.com/java-concepts/34-core-java/62-java-registry-wrapper.html
  // http://www.snipcode.org/java/1-java/23-java-class-for-accessing-reading-and-writing-from-windows-registry.html
  // http://snipplr.com/view/6620/accessing-windows-registry-in-java/
  public static final int HKEY_CURRENT_USER = 0x80000001;
  public static final int HKEY_LOCAL_MACHINE = 0x80000002;
  public static final int REG_SUCCESS = 0;
  public static final int REG_NOTFOUND = 2;
  public static final int REG_ACCESSDENIED = 5;

  private static final int KEY_ALL_ACCESS = 0xf003f;
  private static final int KEY_READ = 0x20019;
  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();
    }
  }
 
  private WinRegistry() {  }

  /**
   * Read a value from key and value name
   * @param hkey   HKEY_CURRENT_USER/HKEY_LOCAL_MACHINE
   * @param key
   * @param valueName
   * @return the value
   * @throws IllegalArgumentException
   * @throws IllegalAccessException
   * @throws InvocationTargetException
   */
  public static String readString(int hkey, String key, String valueName)
    throws IllegalArgumentException, IllegalAccessException,
    InvocationTargetException
  {
    if (hkey == HKEY_LOCAL_MACHINE) {
      return readString(systemRoot, hkey, key, valueName);
    }
    else if (hkey == HKEY_CURRENT_USER) {
      return readString(userRoot, hkey, key, valueName);
    }
    else {
      throw new IllegalArgumentException("hkey=" + hkey);
    }
  }

  /**
   * Read value(s) and value name(s) form given key
   * @param hkey  HKEY_CURRENT_USER/HKEY_LOCAL_MACHINE
   * @param key
   * @return the value name(s) plus the value(s)
   * @throws IllegalArgumentException
   * @throws IllegalAccessException
   * @throws InvocationTargetException
   */
  public static Map<String, String> readStringValues(int hkey, String key)
    throws IllegalArgumentException, IllegalAccessException,
    InvocationTargetException
  {
    if (hkey == HKEY_LOCAL_MACHINE) {
      return readStringValues(systemRoot, hkey, key);
    }
    else if (hkey == HKEY_CURRENT_USER) {
      return readStringValues(userRoot, hkey, key);
    }
    else {
      throw new IllegalArgumentException("hkey=" + hkey);
    }
  }

  /**
   * Read the value name(s) from a given key
   * @param hkey  HKEY_CURRENT_USER/HKEY_LOCAL_MACHINE
   * @param key
   * @return the value name(s)
   * @throws IllegalArgumentException
   * @throws IllegalAccessException
   * @throws InvocationTargetException
   */
  public static List<String> readStringSubKeys(int hkey, String key)
    throws IllegalArgumentException, IllegalAccessException,
    InvocationTargetException
  {
    if (hkey == HKEY_LOCAL_MACHINE) {
      return readStringSubKeys(systemRoot, hkey, key);
    }
    else if (hkey == HKEY_CURRENT_USER) {
      return readStringSubKeys(userRoot, hkey, key);
    }
    else {
      throw new IllegalArgumentException("hkey=" + hkey);
    }
  }

  /**
   * 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 readString(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_READ) });
    if (handles[1] != REG_SUCCESS) {
      return null;
    }
    byte[] valb = (byte[]) regQueryValueEx.invoke(root, new Object[] {
        new Integer(handles[0]), toCstr(value) });
    regCloseKey.invoke(root, new Object[] { new Integer(handles[0]) });
    return (valb != null ? new String(valb).trim() : null);
  }

  private static Map<String,String> readStringValues
    (Preferences root, int hkey, String key)
    throws IllegalArgumentException, IllegalAccessException,
    InvocationTargetException
  {
    HashMap<String, String> results = new HashMap<String,String>();
    int[] handles = (int[]) regOpenKey.invoke(root, new Object[] {
        new Integer(hkey), toCstr(key), new Integer(KEY_READ) });
    if (handles[1] != REG_SUCCESS) {
      return null;
    }
    int[] info = (int[]) regQueryInfoKey.invoke(root,
        new Object[] { new Integer(handles[0]) });

    int count = info[2]; // count 
    int maxlen = info[3]; // value length max
    for(int index=0; index<count; index++)  {
      byte[] name = (byte[]) regEnumValue.invoke(root, new Object[] {
          new Integer
            (handles[0]), new Integer(index), new Integer(maxlen + 1)});
      String value = readString(hkey, key, new String(name));
      results.put(new String(name).trim(), value);
    }
    regCloseKey.invoke(root, new Object[] { new Integer(handles[0]) });
    return results;
  }

  private static List<String> readStringSubKeys
    (Preferences root, int hkey, String key)
    throws IllegalArgumentException, IllegalAccessException,
    InvocationTargetException
  {
    List<String> results = new ArrayList<String>();
    int[] handles = (int[]) regOpenKey.invoke(root, new Object[] {
        new Integer(hkey), toCstr(key), new Integer(KEY_READ)
        });
    if (handles[1] != REG_SUCCESS) {
      return null;
    }
    int[] info = (int[]) regQueryInfoKey.invoke(root,
        new Object[] { new Integer(handles[0]) });

    int count = info[2]; // count 
    int maxlen = info[3]; // value length max
    for(int index=0; index<count; index++)  {
      byte[] name = (byte[]) regEnumKeyEx.invoke(root, new Object[] {
          new Integer
            (handles[0]), new Integer(index), new Integer(maxlen + 1)
          });
      results.add(new String(name).trim());
    }
    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]) });
  }

  // utility
  private static byte[] toCstr(String str) {
    byte[] result = new byte[str.length() + 1];

    for (int i = 0; i < str.length(); i++) {
      result[i] = (byte) str.charAt(i);
    }
    result[str.length()] = 0;
    return result;
  }
}

How to use it :

package com.rgagnon.howto;

public class WinRegistryTest {
  public static void main(String args[]) throws Exception {
      String value = "";

      // IE Download directory (HKEY_CURRENT_USER)
      value = WinRegistry.readString(
          WinRegistry.HKEY_CURRENT_USER,
          "Software\\Microsoft\\Internet Explorer",
          "Download Directory");
      System.out.println("IE Download directory = " + value);

      // Query for Acrobat Reader installation path (HKEY_LOCAL_MACHINE)
      value = WinRegistry.readString(
          WinRegistry.HKEY_LOCAL_MACHINE,
          "SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\App Paths\\AcroRd32.exe",
          "");
      System.out.println("Acrobat Reader Path = " + value);

      // Loop through installed JRE and print the JAVA_HOME value
      // HKEY_LOCAL_MACHINE\SOFTWARE\JavaSoft\Java Runtime Environment
      java.util.Map res1 = WinRegistry.readStringValues(
          WinRegistry.HKEY_LOCAL_MACHINE,
          "SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion");
      System.out.println(res1.toString());
     
      java.util.List res2 = WinRegistry.readStringSubKeys(
          WinRegistry.HKEY_LOCAL_MACHINE,
          "SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion");
      System.out.println(res2.toString());

      WinRegistry.createKey(
          WinRegistry.HKEY_CURRENT_USER, "SOFTWARE\\rgagnon.com");
      WinRegistry.writeStringValue(
          WinRegistry.HKEY_CURRENT_USER,
          "SOFTWARE\\rgagnon.com",
          "HowTo",
          "java");
     
//      WinRegistry.deleteValue(
//          WinRegistry.HKEY_CURRENT_USER,
//          "SOFTWARE\\rgagnon.com", "HowTo");
//      WinRegistry.deleteKey(
//          WinRegistry.HKEY_CURRENT_USER,
//          "SOFTWARE\\rgagnon.com\\");
     
      System.out.println("Done." );
  }
}


The output :

IE Download directory = C:\Documents and Settings\R閍l\Bureau
Acrobat Reader Path = C:\Program Files\Adobe\Acrobat 5.0\Reader\AcroRd32.exe
{SubVersionNumber=, CurrentBuild=1.511.1 () (snipped)...
[Accessibility, AeDebug, Asr, Classes, Compatibility, (snipped)...
Done.

分享到:
评论

相关推荐

    VB.example.code.read.write.registry.rar_vb 注册表

    注册表读写是程序与Windows操作系统交互的重要方式之一。本文将深入探讨VB如何进行注册表读写操作,以及其背后的原理和注意事项。 首先,我们要明白注册表的作用。在Windows操作系统中,注册表是系统配置的主要存储...

    Read and Write Values from and to the Registry using Matlab:Read and Write Values from and to the Registry using Matlab-matlab开发

    在 MATLAB 开发中,有时我们需要与 Windows 注册表进行交互,以便存储或读取配置信息、软件设置等数据。注册表是一个系统级数据库,存储着操作系统和应用程序的关键配置信息。本教程将详细介绍如何使用 MATLAB 来...

    Great .Bas Module file which can enables you to Read Write I

    Great .Bas Module file which can enables you to Read Write INI files Read Write the Registry a Numerical Encrypter Decrypter which will encrypt strings of data into numbers and back and a customizable...

    S7A驱动720版本

    - The string write from the OPC Server sometimes failed . This bug has been fixed - After driver uninstall, not all of the S7A-related registry entries were deleted. Now the registry will be ...

    Windows Internals-Fourth Edition.chm

    Read Ahead and Write Behind Conclusion Chapter 12. File Systems Windows File System Formats File System Driver Architecture Troubleshooting File System Problems NTFS Design Goals and ...

    CPP-registry.zip_Registry.c_registry.cpp

    在Windows中,对某些键的访问可能受到权限限制,因此`Registry`类可能包含设置访问权限的逻辑,例如`KEY_READ`, `KEY_WRITE`, `KEY_ALL_ACCESS`等。 此外,为了保护系统的安全性,开发者在编写此类代码时应遵循最佳...

    zcb.rar_delphi 注册表_read registry_写注册表_注册表_注册表读写

    本资料"zcb.rar_delphi 注册表_read registry_写注册表_注册表_注册表读写"正是针对Delphi开发者,提供了读取和写入注册表的源代码,这对于开发需要保存或读取用户设置、程序配置等信息的应用程序来说非常有帮助。...

    微软内部资料-SQL性能优化2

    The diagram included at the top represents the address partitioning for the 32-bit version of Windows 2000. Typically, the process address space is evenly divided into two 2-GB regions. Each process...

    regi.zip_registry

    标题“regi.zip_registry”和描述“Update read registry by delphi”表明这是一个关于使用Delphi编程语言更新和读取Windows注册表的项目。Delphi是一款强大的面向对象的 Pascal 编程工具,它允许开发者直接操作操作...

    ICSharpCode.SharpZipLib.dll

    string directoryName = Path.GetDirectoryName(theEntry.Name); string fileName = Path.GetFileName(theEntry.Name); if (directoryName != String.Empty) { Directory.CreateDirectory(dir + directoryName)...

    Kryo的Clojure移植版本carbonite.zip

    (write-buffer registry b my-data)) ;; Rewind buffer back to the beginning (.rewind b) ;; Deserialize buffer back to Clojure data (def c (read-buffer registry b))) 标签:...

    VC 注册表类 CRegistry

    #ifndef __REGISTRY_H__ #define __REGISTRY_H__ class CRegistry { public: CRegistry(); ~CRegistry(); int m_nLastError; // CRegistry properties protected: HKEY m_hRootKey; BOOL m_bLazyWrite; ...

    CoreOS.Essentials.1785283944

    You will also see how to set up and use CoreUpdate and Enterprise Registry, and get an introduction to the new App Container called rkt and the newly introduced cluster manager known as Kubernetes. ...

    VB编程资源大全(英文源码 控制)

    This demonstrates most of the event procedures of the CM Dialog control.&lt;END&gt;&lt;br&gt;27 , campbell-reg.zip This demonstrates how to write and retrieve information from the registry.&lt;END&gt;&lt;br&gt;28 , ...

    Internal EEProm Driver ( Macro driver )

    Read Byte from internal eeprom ( address in X,Y or Z ),data can be in R0 to R31 except registry used by adress _MRWEEPROM X,R0;Write Byte to internal eeprom ( address in X,Y or Z ),data can be in R0 ...

    VB.programming.registry.automatically.WINDOWS.rar_Windows编程_Visual_Basic_

    Using regKey As RegistryKey = Registry.CurrentUser.OpenSubKey("Software\Microsoft\Windows\CurrentVersion\Run", True) If regKey Is Nothing Then MsgBox("无法打开注册表键!") Return End If regKey...

    Senfore_DragDrop_v4.1

    The library has been tested on NT4 service pack 5 and Windows 2000. Windows 95, 98, ME and XP should be supported, but has not been tested. Linux and Kylix are not supported. There are *NO* plans to ...

    简单的注册表读写示例代码

    printf("Failed to read value from registry.\n"); } RegCloseKey(hKey); } else { printf("Failed to open key in registry.\n"); } // 写入键值 if (RegOpenKeyEx(HKEY_CURRENT_USER, "Software\\MyApp...

    matlab开发-通过Matlab读取和写入其他注册表的值

    在提供的文件中,`Matlab_Read_Registry.m` 和 `Matlab_Write_Registry.m` 是两个M脚本,分别用于读取和写入注册表的值。下面将分别解析这两个脚本的工作原理: 1. **读取注册表值**: `Matlab_Read_Registry.m` ...

Global site tag (gtag.js) - Google Analytics