<p>How is it possible to read/write to the Windows registry using Java?</p>

[{'answer_id': 62291, 'author': 'Epaga', 'author_id': 6583, 'author_profile': 'https://Stackoverflow.com/users/6583', 'pm_score': 4, 'selected': False, 'text': '<p>Yes, using the java.util.Preferences API, since the Windows implementation of it uses the Registry as a backend.</p>\n<p>In the end it depends on what you\'re wanting to do: storing preferences for your app is what the Preferences does just great. If you\'re wanting to actually change registry keys not having to do with your app, you\'ll need some JNI app, as described by Mark (shameless steal here):</p>\n<blockquote>\n<p>From a quick google:\nCheck the WinPack for JNIWrapper. It has full Windows Registry access support including Reading and Writing.</p>\n<p>The WinPack Demo has Registry Viewer implemented as an example.</p>\n<p>Check at <a href="http://www.teamdev.com/jniwrapper/winpack/#registry_access" rel="noreferrer">http://www.teamdev.com/jniwrapper/winpack/#registry_access</a></p>\n<p>And...</p>\n<p>There is also try JNIRegistry @ <a href="http://www.trustice.com/java/jnireg/" rel="noreferrer">http://www.trustice.com/java/jnireg/</a></p>\n<p>There is also the option of invoking an external app, which is responsible for reading / writing the registry.</p>\n</blockquote>\n'}, {'answer_id': 62299, 'author': 'Mark Ingram', 'author_id': 986, 'author_profile': 'https://Stackoverflow.com/users/986', 'pm_score': 4, 'selected': False, 'text': '<p>From a quick google:</p>\n\n<blockquote>\n  <p>Check the WinPack for JNIWrapper. It\n  has full Windows Registry access\n  support including Reading and Writing.</p>\n  \n  <p>The WinPack Demo has Registry Viewer\n  implemented as an example.</p>\n  \n  <p>Check at\n  <a href="http://www.teamdev.com/jniwrapper/winpack/#registry_access" rel="noreferrer">http://www.teamdev.com/jniwrapper/winpack/#registry_access</a></p>\n</blockquote>\n\n<p>And...</p>\n\n<blockquote>\n  <p>There is also try JNIRegistry @\n  <a href="http://www.trustice.com/java/jnireg/" rel="noreferrer">http://www.trustice.com/java/jnireg/</a></p>\n</blockquote>\n\n<p>There is also the option of invoking an external app, which is responsible for reading / writing the registry.</p>\n'}, {'answer_id': 62312, 'author': 'Vinko Vrsalovic', 'author_id': 5190, 'author_profile': 'https://Stackoverflow.com/users/5190', 'pm_score': 2, 'selected': False, 'text': "<p>The Preferences API approach does not give you access to all the branches of the registry. In fact, it only gives you access to where the Preferences API stores its, well, preferences. It's not a generic registry handling API, like .NET's</p>\n\n<p>To read/write every key I guess JNI or an external tool would be the approach to take, as Mark shows.</p>\n"}, {'answer_id': 62690, 'author': 'Ignat', 'author_id': 119889, 'author_profile': 'https://Stackoverflow.com/users/119889', 'pm_score': 3, 'selected': False, 'text': '<p>There are few JNDI service providers to work with windows registry.</p>\n\n<p>One could observe <a href="https://web.archive.org/web/20120801053337/http://java.sun.com/products/jndi/serviceproviders.html" rel="nofollow noreferrer">http://java.sun.com/products/jndi/serviceproviders.html</a>.</p>\n'}, {'answer_id': 63231, 'author': 'Alex Argo', 'author_id': 5885, 'author_profile': 'https://Stackoverflow.com/users/5885', 'pm_score': 5, 'selected': False, 'text': '<p>I\'ve done this before using <a href="http://sourceforge.net/projects/jregistrykey/" rel="noreferrer" title="jRegistryKey">jRegistryKey</a>. It is an LGPL Java/JNI library that can do what you need. Here\'s an example of how I used it to enabled Registry editing through regedit and also the "Show Folder Options" option for myself in Windows via the registry.</p>\n\n<pre><code>import java.io.File;\nimport ca.beq.util.win32.registry.RegistryKey;\nimport ca.beq.util.win32.registry.RegistryValue;\nimport ca.beq.util.win32.registry.RootKey;\nimport ca.beq.util.win32.registry.ValueType;\n\n\npublic class FixStuff {\n\nprivate static final String REGEDIT_KEY = "Software\\\\Microsoft\\\\Windows\\\\CurrentVersion\\\\Policies\\\\System";\nprivate static final String REGEDIT_VALUE = "DisableRegistryTools";\nprivate static final String REGISTRY_LIBRARY_PATH = "\\\\lib\\\\jRegistryKey.dll";\nprivate static final String FOLDER_OPTIONS_KEY = "Software\\\\Microsoft\\\\Windows\\\\CurrentVersion\\\\Policies\\\\Explorer";\nprivate static final String FOLDER_OPTIONS_VALUE = "NoFolderOptions";\n\npublic static void main(String[] args) {\n    //Load JNI library\n    RegistryKey.initialize( new File(".").getAbsolutePath()+REGISTRY_LIBRARY_PATH );\n\n    enableRegistryEditing(true);        \n    enableShowFolderOptions(true);\n}\n\nprivate static void enableShowFolderOptions(boolean enable) {\n    RegistryKey key = new RegistryKey(RootKey.HKEY_CURRENT_USER,FOLDER_OPTIONS_KEY);\n    RegistryKey key2 = new RegistryKey(RootKey.HKEY_LOCAL_MACHINE,FOLDER_OPTIONS_KEY);\n    RegistryValue value = new RegistryValue();\n    value.setName(FOLDER_OPTIONS_VALUE);\n    value.setType(ValueType.REG_DWORD_LITTLE_ENDIAN);\n    value.setData(enable?0:1);\n\n    if(key.hasValue(FOLDER_OPTIONS_VALUE)) {\n        key.setValue(value);\n    }\n    if(key2.hasValue(FOLDER_OPTIONS_VALUE)) {\n        key2.setValue(value);\n    }           \n}\n\nprivate static void enableRegistryEditing(boolean enable) {\n    RegistryKey key = new RegistryKey(RootKey.HKEY_CURRENT_USER,REGEDIT_KEY);\n    RegistryValue value = new RegistryValue();\n    value.setName(REGEDIT_VALUE);\n    value.setType(ValueType.REG_DWORD_LITTLE_ENDIAN);\n    value.setData(enable?0:1);\n\n    if(key.hasValue(REGEDIT_VALUE)) {\n        key.setValue(value);\n    }\n}\n\n}\n</code></pre>\n'}, {'answer_id': 876862, 'author': 'Community', 'author_id': -1, 'author_profile': 'https://Stackoverflow.com/users/-1', 'pm_score': 0, 'selected': False, 'text': '<blockquote>\n  <p>The WinPack Demo has Registry Viewer\n  implemented as an example.</p>\n  \n  <p>Check at\n  <a href="http://www.jniwrapper.com/winpack_features.jsp#registry" rel="nofollow noreferrer">http://www.jniwrapper.com/winpack_features.jsp#registry</a></p>\n</blockquote>\n\n<p>BTW, WinPack has been moved to the following address:</p>\n\n<p><a href="http://www.teamdev.com/jniwrapper/winpack/" rel="nofollow noreferrer">http://www.teamdev.com/jniwrapper/winpack/</a></p>\n'}, {'answer_id': 878336, 'author': 'Peter Smith', 'author_id': 103715, 'author_profile': 'https://Stackoverflow.com/users/103715', 'pm_score': 2, 'selected': False, 'text': '<p>You could try <a href="http://winrun4j.sourceforge.net/" rel="nofollow noreferrer" title="WinRun4J">WinRun4J</a>. This is a windows java launcher and service host but it also provides a library for accessing the registry.</p>\n\n<p>(btw I work on this project so let me know if you have any questions)</p>\n'}, {'answer_id': 1982033, 'author': 'Oleg Ryaboy', 'author_id': 205711, 'author_profile': 'https://Stackoverflow.com/users/205711', 'pm_score': 7, 'selected': False, 'text': '<p>You don\'t actually need a 3rd party package. Windows has a reg utility for all registry operations. To get the command format, go to the DOS propmt and type:</p>\n\n<pre><code>reg /?\n</code></pre>\n\n<p>You can invoke <em>reg</em> through the Runtime class:</p>\n\n<pre><code>Runtime.getRuntime().exec("reg &lt;your parameters here&gt;");\n</code></pre>\n\n<p>Editing keys and adding new ones is straightforward using the command above. To read the registry, you need to get <em>reg</em>\'s output, and it\'s a little tricky. Here\'s the code:</p>\n\n<pre><code>import java.io.IOException;\nimport java.io.InputStream;\nimport java.io.StringWriter;\n\n/**\n * @author Oleg Ryaboy, based on work by Miguel Enriquez \n */\npublic class WindowsReqistry {\n\n    /**\n     * \n     * @param location path in the registry\n     * @param key registry key\n     * @return registry value or null if not found\n     */\n    public static final String readRegistry(String location, String key){\n        try {\n            // Run reg query, then read output with StreamReader (internal class)\n            Process process = Runtime.getRuntime().exec("reg query " + \n                    \'"\'+ location + "\\" /v " + key);\n\n            StreamReader reader = new StreamReader(process.getInputStream());\n            reader.start();\n            process.waitFor();\n            reader.join();\n            String output = reader.getResult();\n\n            // Output has the following format:\n            // \\n&lt;Version information&gt;\\n\\n&lt;key&gt;\\t&lt;registry type&gt;\\t&lt;value&gt;\n            if( ! output.contains("\\t")){\n                    return null;\n            }\n\n            // Parse out the value\n            String[] parsed = output.split("\\t");\n            return parsed[parsed.length-1];\n        }\n        catch (Exception e) {\n            return null;\n        }\n\n    }\n\n    static class StreamReader extends Thread {\n        private InputStream is;\n        private StringWriter sw= new StringWriter();\n\n        public StreamReader(InputStream is) {\n            this.is = is;\n        }\n\n        public void run() {\n            try {\n                int c;\n                while ((c = is.read()) != -1)\n                    sw.write(c);\n            }\n            catch (IOException e) { \n        }\n        }\n\n        public String getResult() {\n            return sw.toString();\n        }\n    }\n    public static void main(String[] args) {\n\n        // Sample usage\n        String value = WindowsReqistry.readRegistry("HKCU\\\\Software\\\\Microsoft\\\\Windows\\\\CurrentVersion\\\\" \n                 + "Explorer\\\\Shell Folders", "Personal");\n        System.out.println(value);\n    }\n}\n</code></pre>\n\n<hr>\n'}, {'answer_id': 5841923, 'author': 'Tom Anderson', 'author_id': 116639, 'author_profile': 'https://Stackoverflow.com/users/116639', 'pm_score': 3, 'selected': False, 'text': '<p>As has been noted, the Preferences API uses the registry to store preferences, but cannot be used to access the whole registry.</p>\n\n<p>However, a pirate called David Croft has worked out that it\'s possible to use methods in Sun\'s implementation of the Preferences API for <a href="http://www.davidc.net/programming/java/reading-windows-registry-java-without-jni" rel="nofollow">reading the Windows registry from Java without JNI</a>. There are some dangers to that, but it is worth a look.</p>\n'}, {'answer_id': 5902131, 'author': 'gousli', 'author_id': 740494, 'author_profile': 'https://Stackoverflow.com/users/740494', 'pm_score': 3, 'selected': False, 'text': '<p>Here\'s a modified version of Oleg\'s solution.  I noticed that on my system (Windows server 2003), the output of "reg query" is not separated by tabs (\'\\t\'), but by 4 spaces.</p>\n\n<p>I also simplified the solution, as a thread is not required.</p>\n\n<pre><code>public static final String readRegistry(String location, String key)\n{\n  try\n  {\n      // Run reg query, then read output with StreamReader (internal class)\n      Process process = Runtime.getRuntime().exec("reg query " + \n              \'"\'+ location + "\\" /v " + key);\n\n      InputStream is = process.getInputStream();\n      StringBuilder sw = new StringBuilder();\n\n      try\n      {\n         int c;\n         while ((c = is.read()) != -1)\n             sw.append((char)c);\n      }\n      catch (IOException e)\n      { \n      }\n\n      String output = sw.toString();\n\n      // Output has the following format:\n      // \\n&lt;Version information&gt;\\n\\n&lt;key&gt;    &lt;registry type&gt;    &lt;value&gt;\\r\\n\\r\\n\n      int i = output.indexOf("REG_SZ");\n      if (i == -1)\n      {\n          return null;\n      }\n\n      sw = new StringBuilder();\n      i += 6; // skip REG_SZ\n\n      // skip spaces or tabs\n      for (;;)\n      {\n         if (i &gt; output.length())\n             break;\n         char c = output.charAt(i);\n         if (c != \' \' &amp;&amp; c != \'\\t\')\n             break;\n         ++i;\n      }\n\n      // take everything until end of line\n      for (;;)\n      {\n         if (i &gt; output.length())\n             break;\n         char c = output.charAt(i);\n         if (c == \'\\r\' || c == \'\\n\')\n             break;\n         sw.append(c);\n         ++i;\n      }\n\n      return sw.toString();\n  }\n  catch (Exception e)\n  {\n      return null;\n  }\n</code></pre>\n\n<p>}</p>\n'}, {'answer_id': 6028547, 'author': 'Vishal', 'author_id': 390550, 'author_profile': 'https://Stackoverflow.com/users/390550', 'pm_score': -1, 'selected': False, 'text': '<p>I prefer using <a href="https://docs.oracle.com/javase/8/docs/technotes/guides/preferences/overview.html" rel="nofollow">java.util.prefs.Preferences</a> class.</p>\n\n<p>A simple example would be </p>\n\n<pre><code>// Write Operation\nPreferences p = Preferences.userRoot();\np.put("key","value"); \n// also there are various other methods such as putByteArray(), putDouble() etc.\np.flush();\n//Read Operation\nPreferences p = Preferences.userRoot();\nString value = p.get("key");\n</code></pre>\n'}, {'answer_id': 6163701, 'author': 'David', 'author_id': 656963, 'author_profile': 'https://Stackoverflow.com/users/656963', 'pm_score': 8, 'selected': False, 'text': '<p>I know this question is old, but it is the first search result on google to "java read/write to registry".  Recently I found this amazing piece of code which:</p>\n\n<ul>\n<li>Can read/write to ANY part of the registry. </li>\n<li>DOES NOT USE JNI.</li>\n<li>DOES NOT USE ANY 3rd PARTY/EXTERNAL APPLICATIONS TO WORK.</li>\n<li>DOES NOT USE THE WINDOWS API (directly)</li>\n</ul>\n\n<p>This is pure, Java code.</p>\n\n<p>It uses reflection to work, by actually accessing the private methods in the <code>java.util.prefs.Preferences</code> class. The internals of this class are complicated, but the class itself is very easy to use.</p>\n\n<p>For example, the following code obtains the exact windows distribution <strong>from the registry</strong>:</p>\n\n<pre><code>String value = WinRegistry.readString (\n    WinRegistry.HKEY_LOCAL_MACHINE,                             //HKEY\n   "SOFTWARE\\\\Microsoft\\\\Windows NT\\\\CurrentVersion",           //Key\n   "ProductName");                                              //ValueName\n    System.out.println("Windows Distribution = " + value);          \n</code></pre>\n\n<p>Here is the original class. Just copy paste it and it should work:</p>\n\n<pre><code>import java.lang.reflect.InvocationTargetException;\nimport java.lang.reflect.Method;\nimport java.util.HashMap;\nimport java.util.Map;\nimport java.util.ArrayList;\nimport java.util.List;\nimport java.util.prefs.Preferences;\n\npublic class WinRegistry {\n  public static final int HKEY_CURRENT_USER = 0x80000001;\n  public static final int HKEY_LOCAL_MACHINE = 0x80000002;\n  public static final int REG_SUCCESS = 0;\n  public static final int REG_NOTFOUND = 2;\n  public static final int REG_ACCESSDENIED = 5;\n\n  private static final int KEY_ALL_ACCESS = 0xf003f;\n  private static final int KEY_READ = 0x20019;\n  private static final Preferences userRoot = Preferences.userRoot();\n  private static final Preferences systemRoot = Preferences.systemRoot();\n  private static final Class&lt;? extends Preferences&gt; userClass = userRoot.getClass();\n  private static final Method regOpenKey;\n  private static final Method regCloseKey;\n  private static final Method regQueryValueEx;\n  private static final Method regEnumValue;\n  private static final Method regQueryInfoKey;\n  private static final Method regEnumKeyEx;\n  private static final Method regCreateKeyEx;\n  private static final Method regSetValueEx;\n  private static final Method regDeleteKey;\n  private static final Method regDeleteValue;\n\n  static {\n    try {\n      regOpenKey = userClass.getDeclaredMethod("WindowsRegOpenKey",\n          new Class[] { int.class, byte[].class, int.class });\n      regOpenKey.setAccessible(true);\n      regCloseKey = userClass.getDeclaredMethod("WindowsRegCloseKey",\n          new Class[] { int.class });\n      regCloseKey.setAccessible(true);\n      regQueryValueEx = userClass.getDeclaredMethod("WindowsRegQueryValueEx",\n          new Class[] { int.class, byte[].class });\n      regQueryValueEx.setAccessible(true);\n      regEnumValue = userClass.getDeclaredMethod("WindowsRegEnumValue",\n          new Class[] { int.class, int.class, int.class });\n      regEnumValue.setAccessible(true);\n      regQueryInfoKey = userClass.getDeclaredMethod("WindowsRegQueryInfoKey1",\n          new Class[] { int.class });\n      regQueryInfoKey.setAccessible(true);\n      regEnumKeyEx = userClass.getDeclaredMethod(  \n          "WindowsRegEnumKeyEx", new Class[] { int.class, int.class,  \n              int.class });  \n      regEnumKeyEx.setAccessible(true);\n      regCreateKeyEx = userClass.getDeclaredMethod(  \n          "WindowsRegCreateKeyEx", new Class[] { int.class,  \n              byte[].class });  \n      regCreateKeyEx.setAccessible(true);  \n      regSetValueEx = userClass.getDeclaredMethod(  \n          "WindowsRegSetValueEx", new Class[] { int.class,  \n              byte[].class, byte[].class });  \n      regSetValueEx.setAccessible(true); \n      regDeleteValue = userClass.getDeclaredMethod(  \n          "WindowsRegDeleteValue", new Class[] { int.class,  \n              byte[].class });  \n      regDeleteValue.setAccessible(true); \n      regDeleteKey = userClass.getDeclaredMethod(  \n          "WindowsRegDeleteKey", new Class[] { int.class,  \n              byte[].class });  \n      regDeleteKey.setAccessible(true); \n    }\n    catch (Exception e) {\n      throw new RuntimeException(e);\n    }\n  }\n\n  private WinRegistry() {  }\n\n  /**\n   * Read a value from key and value name\n   * @param hkey   HKEY_CURRENT_USER/HKEY_LOCAL_MACHINE\n   * @param key\n   * @param valueName\n   * @return the value\n   * @throws IllegalArgumentException\n   * @throws IllegalAccessException\n   * @throws InvocationTargetException\n   */\n  public static String readString(int hkey, String key, String valueName) \n    throws IllegalArgumentException, IllegalAccessException,\n    InvocationTargetException \n  {\n    if (hkey == HKEY_LOCAL_MACHINE) {\n      return readString(systemRoot, hkey, key, valueName);\n    }\n    else if (hkey == HKEY_CURRENT_USER) {\n      return readString(userRoot, hkey, key, valueName);\n    }\n    else {\n      throw new IllegalArgumentException("hkey=" + hkey);\n    }\n  }\n\n  /**\n   * Read value(s) and value name(s) form given key \n   * @param hkey  HKEY_CURRENT_USER/HKEY_LOCAL_MACHINE\n   * @param key\n   * @return the value name(s) plus the value(s)\n   * @throws IllegalArgumentException\n   * @throws IllegalAccessException\n   * @throws InvocationTargetException\n   */\n  public static Map&lt;String, String&gt; readStringValues(int hkey, String key) \n    throws IllegalArgumentException, IllegalAccessException,\n    InvocationTargetException \n  {\n    if (hkey == HKEY_LOCAL_MACHINE) {\n      return readStringValues(systemRoot, hkey, key);\n    }\n    else if (hkey == HKEY_CURRENT_USER) {\n      return readStringValues(userRoot, hkey, key);\n    }\n    else {\n      throw new IllegalArgumentException("hkey=" + hkey);\n    }\n  }\n\n  /**\n   * Read the value name(s) from a given key\n   * @param hkey  HKEY_CURRENT_USER/HKEY_LOCAL_MACHINE\n   * @param key\n   * @return the value name(s)\n   * @throws IllegalArgumentException\n   * @throws IllegalAccessException\n   * @throws InvocationTargetException\n   */\n  public static List&lt;String&gt; readStringSubKeys(int hkey, String key) \n    throws IllegalArgumentException, IllegalAccessException,\n    InvocationTargetException \n  {\n    if (hkey == HKEY_LOCAL_MACHINE) {\n      return readStringSubKeys(systemRoot, hkey, key);\n    }\n    else if (hkey == HKEY_CURRENT_USER) {\n      return readStringSubKeys(userRoot, hkey, key);\n    }\n    else {\n      throw new IllegalArgumentException("hkey=" + hkey);\n    }\n  }\n\n  /**\n   * Create a key\n   * @param hkey  HKEY_CURRENT_USER/HKEY_LOCAL_MACHINE\n   * @param key\n   * @throws IllegalArgumentException\n   * @throws IllegalAccessException\n   * @throws InvocationTargetException\n   */\n  public static void createKey(int hkey, String key) \n    throws IllegalArgumentException, IllegalAccessException,\n    InvocationTargetException \n  {\n    int [] ret;\n    if (hkey == HKEY_LOCAL_MACHINE) {\n      ret = createKey(systemRoot, hkey, key);\n      regCloseKey.invoke(systemRoot, new Object[] { new Integer(ret[0]) });\n    }\n    else if (hkey == HKEY_CURRENT_USER) {\n      ret = createKey(userRoot, hkey, key);\n      regCloseKey.invoke(userRoot, new Object[] { new Integer(ret[0]) });\n    }\n    else {\n      throw new IllegalArgumentException("hkey=" + hkey);\n    }\n    if (ret[1] != REG_SUCCESS) {\n      throw new IllegalArgumentException("rc=" + ret[1] + "  key=" + key);\n    }\n  }\n\n  /**\n   * Write a value in a given key/value name\n   * @param hkey\n   * @param key\n   * @param valueName\n   * @param value\n   * @throws IllegalArgumentException\n   * @throws IllegalAccessException\n   * @throws InvocationTargetException\n   */\n  public static void writeStringValue\n    (int hkey, String key, String valueName, String value) \n    throws IllegalArgumentException, IllegalAccessException,\n    InvocationTargetException \n  {\n    if (hkey == HKEY_LOCAL_MACHINE) {\n      writeStringValue(systemRoot, hkey, key, valueName, value);\n    }\n    else if (hkey == HKEY_CURRENT_USER) {\n      writeStringValue(userRoot, hkey, key, valueName, value);\n    }\n    else {\n      throw new IllegalArgumentException("hkey=" + hkey);\n    }\n  }\n\n  /**\n   * Delete a given key\n   * @param hkey\n   * @param key\n   * @throws IllegalArgumentException\n   * @throws IllegalAccessException\n   * @throws InvocationTargetException\n   */\n  public static void deleteKey(int hkey, String key) \n    throws IllegalArgumentException, IllegalAccessException,\n    InvocationTargetException \n  {\n    int rc = -1;\n    if (hkey == HKEY_LOCAL_MACHINE) {\n      rc = deleteKey(systemRoot, hkey, key);\n    }\n    else if (hkey == HKEY_CURRENT_USER) {\n      rc = deleteKey(userRoot, hkey, key);\n    }\n    if (rc != REG_SUCCESS) {\n      throw new IllegalArgumentException("rc=" + rc + "  key=" + key);\n    }\n  }\n\n  /**\n   * delete a value from a given key/value name\n   * @param hkey\n   * @param key\n   * @param value\n   * @throws IllegalArgumentException\n   * @throws IllegalAccessException\n   * @throws InvocationTargetException\n   */\n  public static void deleteValue(int hkey, String key, String value) \n    throws IllegalArgumentException, IllegalAccessException,\n    InvocationTargetException \n  {\n    int rc = -1;\n    if (hkey == HKEY_LOCAL_MACHINE) {\n      rc = deleteValue(systemRoot, hkey, key, value);\n    }\n    else if (hkey == HKEY_CURRENT_USER) {\n      rc = deleteValue(userRoot, hkey, key, value);\n    }\n    if (rc != REG_SUCCESS) {\n      throw new IllegalArgumentException("rc=" + rc + "  key=" + key + "  value=" + value);\n    }\n  }\n\n  // =====================\n\n  private static int deleteValue\n    (Preferences root, int hkey, String key, String value)\n    throws IllegalArgumentException, IllegalAccessException,\n    InvocationTargetException \n  {\n    int[] handles = (int[]) regOpenKey.invoke(root, new Object[] {\n        new Integer(hkey), toCstr(key), new Integer(KEY_ALL_ACCESS) });\n    if (handles[1] != REG_SUCCESS) {\n      return handles[1];  // can be REG_NOTFOUND, REG_ACCESSDENIED\n    }\n    int rc =((Integer) regDeleteValue.invoke(root,  \n        new Object[] { \n          new Integer(handles[0]), toCstr(value) \n          })).intValue();\n    regCloseKey.invoke(root, new Object[] { new Integer(handles[0]) });\n    return rc;\n  }\n\n  private static int deleteKey(Preferences root, int hkey, String key) \n    throws IllegalArgumentException, IllegalAccessException,\n    InvocationTargetException \n  {\n    int rc =((Integer) regDeleteKey.invoke(root,  \n        new Object[] { new Integer(hkey), toCstr(key) })).intValue();\n    return rc;  // can REG_NOTFOUND, REG_ACCESSDENIED, REG_SUCCESS\n  }\n\n  private static String readString(Preferences root, int hkey, String key, String value)\n    throws IllegalArgumentException, IllegalAccessException,\n    InvocationTargetException \n  {\n    int[] handles = (int[]) regOpenKey.invoke(root, new Object[] {\n        new Integer(hkey), toCstr(key), new Integer(KEY_READ) });\n    if (handles[1] != REG_SUCCESS) {\n      return null; \n    }\n    byte[] valb = (byte[]) regQueryValueEx.invoke(root, new Object[] {\n        new Integer(handles[0]), toCstr(value) });\n    regCloseKey.invoke(root, new Object[] { new Integer(handles[0]) });\n    return (valb != null ? new String(valb).trim() : null);\n  }\n\n  private static Map&lt;String,String&gt; readStringValues\n    (Preferences root, int hkey, String key)\n    throws IllegalArgumentException, IllegalAccessException,\n    InvocationTargetException \n  {\n    HashMap&lt;String, String&gt; results = new HashMap&lt;String,String&gt;();\n    int[] handles = (int[]) regOpenKey.invoke(root, new Object[] {\n        new Integer(hkey), toCstr(key), new Integer(KEY_READ) });\n    if (handles[1] != REG_SUCCESS) {\n      return null;\n    }\n    int[] info = (int[]) regQueryInfoKey.invoke(root,\n        new Object[] { new Integer(handles[0]) });\n\n    int count = info[0]; // count  \n    int maxlen = info[3]; // value length max\n    for(int index=0; index&lt;count; index++)  {\n      byte[] name = (byte[]) regEnumValue.invoke(root, new Object[] {\n          new Integer\n            (handles[0]), new Integer(index), new Integer(maxlen + 1)});\n      String value = readString(hkey, key, new String(name));\n      results.put(new String(name).trim(), value);\n    }\n    regCloseKey.invoke(root, new Object[] { new Integer(handles[0]) });\n    return results;\n  }\n\n  private static List&lt;String&gt; readStringSubKeys\n    (Preferences root, int hkey, String key)\n    throws IllegalArgumentException, IllegalAccessException,\n    InvocationTargetException \n  {\n    List&lt;String&gt; results = new ArrayList&lt;String&gt;();\n    int[] handles = (int[]) regOpenKey.invoke(root, new Object[] {\n        new Integer(hkey), toCstr(key), new Integer(KEY_READ) \n        });\n    if (handles[1] != REG_SUCCESS) {\n      return null;\n    }\n    int[] info = (int[]) regQueryInfoKey.invoke(root,\n        new Object[] { new Integer(handles[0]) });\n\n    int count  = info[0]; // Fix: info[2] was being used here with wrong results. Suggested by davenpcj, confirmed by Petrucio\n    int maxlen = info[3]; // value length max\n    for(int index=0; index&lt;count; index++)  {\n      byte[] name = (byte[]) regEnumKeyEx.invoke(root, new Object[] {\n          new Integer\n            (handles[0]), new Integer(index), new Integer(maxlen + 1)\n          });\n      results.add(new String(name).trim());\n    }\n    regCloseKey.invoke(root, new Object[] { new Integer(handles[0]) });\n    return results;\n  }\n\n  private static int [] createKey(Preferences root, int hkey, String key)\n    throws IllegalArgumentException, IllegalAccessException,\n    InvocationTargetException \n  {\n    return  (int[]) regCreateKeyEx.invoke(root,\n        new Object[] { new Integer(hkey), toCstr(key) });\n  }\n\n  private static void writeStringValue \n    (Preferences root, int hkey, String key, String valueName, String value) \n    throws IllegalArgumentException, IllegalAccessException,\n    InvocationTargetException \n  {\n    int[] handles = (int[]) regOpenKey.invoke(root, new Object[] {\n        new Integer(hkey), toCstr(key), new Integer(KEY_ALL_ACCESS) });\n\n    regSetValueEx.invoke(root,  \n        new Object[] { \n          new Integer(handles[0]), toCstr(valueName), toCstr(value) \n          }); \n    regCloseKey.invoke(root, new Object[] { new Integer(handles[0]) });\n  }\n\n  // utility\n  private static byte[] toCstr(String str) {\n    byte[] result = new byte[str.length() + 1];\n\n    for (int i = 0; i &lt; str.length(); i++) {\n      result[i] = (byte) str.charAt(i);\n    }\n    result[str.length()] = 0;\n    return result;\n  }\n}\n</code></pre>\n\n<p>Original Author: Apache.</p>\n\n<p>Library Source: <a href="https://github.com/apache/npanday/tree/trunk/components/dotnet-registry/src/main/java/npanday/registry" rel="noreferrer">https://github.com/apache/npanday/tree/trunk/components/dotnet-registry/src/main/java/npanday/registry</a></p>\n'}, {'answer_id': 6287763, 'author': 'John McCarthy', 'author_id': 277307, 'author_profile': 'https://Stackoverflow.com/users/277307', 'pm_score': 6, 'selected': False, 'text': '<p><a href="https://github.com/java-native-access/jna" rel="noreferrer" title="JNA Home">Java Native Access (JNA)</a> is an excellent project for working with native libraries and has support for the Windows registry in the platform library (platform.jar) through <a href="https://java-native-access.github.io/jna/5.4.0/javadoc/com/sun/jna/platform/win32/Advapi32Util.html" rel="noreferrer" title="JNA Advapi32Util javadoc">Advapi32Util</a> and <a href="https://java-native-access.github.io/jna/5.4.0/javadoc/com/sun/jna/platform/win32/Advapi32.html" rel="noreferrer" title="JNA Advapi32 javadoc">Advapi32</a>.</p>\n\n<p><strong>Update:</strong> Here\'s a snippet with some examples of how easy it is to use JNA to work with the Windows registry using JNA 3.4.1,</p>\n\n<pre><code>import com.sun.jna.platform.win32.Advapi32Util;\nimport com.sun.jna.platform.win32.WinReg;\n\npublic class WindowsRegistrySnippet {\n    public static void main(String[] args) {\n        // Read a string\n        String productName = Advapi32Util.registryGetStringValue(\n            WinReg.HKEY_LOCAL_MACHINE, "SOFTWARE\\\\Microsoft\\\\Windows NT\\\\CurrentVersion", "ProductName");\n        System.out.printf("Product Name: %s\\n", productName);\n\n        // Read an int (&amp; 0xFFFFFFFFL for large unsigned int)\n        int timeout = Advapi32Util.registryGetIntValue(\n            WinReg.HKEY_LOCAL_MACHINE, "SOFTWARE\\\\Microsoft\\\\Windows NT\\\\CurrentVersion\\\\Windows", "ShutdownWarningDialogTimeout");\n        System.out.printf("Shutdown Warning Dialog Timeout: %d (%d as unsigned long)\\n", timeout, timeout &amp; 0xFFFFFFFFL);\n\n        // Create a key and write a string\n        Advapi32Util.registryCreateKey(WinReg.HKEY_CURRENT_USER, "SOFTWARE\\\\StackOverflow");\n        Advapi32Util.registrySetStringValue(WinReg.HKEY_CURRENT_USER, "SOFTWARE\\\\StackOverflow", "url", "http://stackoverflow.com/a/6287763/277307");\n\n        // Delete a key\n        Advapi32Util.registryDeleteKey(WinReg.HKEY_CURRENT_USER, "SOFTWARE\\\\StackOverflow");\n    }\n}\n</code></pre>\n'}, {'answer_id': 8955801, 'author': 'Johnydep', 'author_id': 750965, 'author_profile': 'https://Stackoverflow.com/users/750965', 'pm_score': 0, 'selected': False, 'text': '<p>Although this is pretty old, but i guess the better utility to use on windows platform would be <code>regini</code> :</p>\n\n<p>A single call to process: </p>\n\n<pre><code>Runtime.getRuntime().exec("regini &lt;your script file abs path here&gt;");\n</code></pre>\n\n<p>will do all the magic. I have tried it, while making jar as windows service using servany.exe which requires changes to made in registry for adding javaw.exe arguments and it works perfectly. You might want to read this: <a href="http://support.microsoft.com/kb/264584" rel="nofollow">http://support.microsoft.com/kb/264584</a></p>\n'}, {'answer_id': 11854901, 'author': 'Petrucio', 'author_id': 828681, 'author_profile': 'https://Stackoverflow.com/users/828681', 'pm_score': 5, 'selected': False, 'text': '<p>I\'ve incremented the Pure java code originally posted by David to allow acessing the 32-bits section of the registry from a 64-bit JVM, and vice-versa. I don\'t think any of the other answers address this.</p>\n\n<p>Here it is:</p>\n\n<pre><code>/**\n * Pure Java Windows Registry access.\n * Modified by petrucio@stackoverflow(828681) to add support for\n * reading (and writing but not creating/deleting keys) the 32-bits\n * registry view from a 64-bits JVM (KEY_WOW64_32KEY)\n * and 64-bits view from a 32-bits JVM (KEY_WOW64_64KEY).\n *****************************************************************************/\n\nimport java.lang.reflect.InvocationTargetException;\nimport java.lang.reflect.Method;\nimport java.util.HashMap;\nimport java.util.Map;\nimport java.util.ArrayList;\nimport java.util.List;\nimport java.util.prefs.Preferences;\n\npublic class WinRegistry {\n  public static final int HKEY_CURRENT_USER = 0x80000001;\n  public static final int HKEY_LOCAL_MACHINE = 0x80000002;\n  public static final int REG_SUCCESS = 0;\n  public static final int REG_NOTFOUND = 2;\n  public static final int REG_ACCESSDENIED = 5;\n\n  public static final int KEY_WOW64_32KEY = 0x0200;\n  public static final int KEY_WOW64_64KEY = 0x0100;\n\n  private static final int KEY_ALL_ACCESS = 0xf003f;\n  private static final int KEY_READ = 0x20019;\n  private static Preferences userRoot = Preferences.userRoot();\n  private static Preferences systemRoot = Preferences.systemRoot();\n  private static Class&lt;? extends Preferences&gt; userClass = userRoot.getClass();\n  private static Method regOpenKey = null;\n  private static Method regCloseKey = null;\n  private static Method regQueryValueEx = null;\n  private static Method regEnumValue = null;\n  private static Method regQueryInfoKey = null;\n  private static Method regEnumKeyEx = null;\n  private static Method regCreateKeyEx = null;\n  private static Method regSetValueEx = null;\n  private static Method regDeleteKey = null;\n  private static Method regDeleteValue = null;\n\n  static {\n    try {\n      regOpenKey     = userClass.getDeclaredMethod("WindowsRegOpenKey",     new Class[] { int.class, byte[].class, int.class });\n      regOpenKey.setAccessible(true);\n      regCloseKey    = userClass.getDeclaredMethod("WindowsRegCloseKey",    new Class[] { int.class });\n      regCloseKey.setAccessible(true);\n      regQueryValueEx= userClass.getDeclaredMethod("WindowsRegQueryValueEx",new Class[] { int.class, byte[].class });\n      regQueryValueEx.setAccessible(true);\n      regEnumValue   = userClass.getDeclaredMethod("WindowsRegEnumValue",   new Class[] { int.class, int.class, int.class });\n      regEnumValue.setAccessible(true);\n      regQueryInfoKey=userClass.getDeclaredMethod("WindowsRegQueryInfoKey1",new Class[] { int.class });\n      regQueryInfoKey.setAccessible(true);\n      regEnumKeyEx   = userClass.getDeclaredMethod("WindowsRegEnumKeyEx",   new Class[] { int.class, int.class, int.class });  \n      regEnumKeyEx.setAccessible(true);\n      regCreateKeyEx = userClass.getDeclaredMethod("WindowsRegCreateKeyEx", new Class[] { int.class, byte[].class });\n      regCreateKeyEx.setAccessible(true);  \n      regSetValueEx  = userClass.getDeclaredMethod("WindowsRegSetValueEx",  new Class[] { int.class, byte[].class, byte[].class });  \n      regSetValueEx.setAccessible(true); \n      regDeleteValue = userClass.getDeclaredMethod("WindowsRegDeleteValue", new Class[] { int.class, byte[].class });  \n      regDeleteValue.setAccessible(true); \n      regDeleteKey   = userClass.getDeclaredMethod("WindowsRegDeleteKey",   new Class[] { int.class, byte[].class });  \n      regDeleteKey.setAccessible(true); \n    }\n    catch (Exception e) {\n      e.printStackTrace();\n    }\n  }\n\n  private WinRegistry() {  }\n\n  /**\n   * Read a value from key and value name\n   * @param hkey   HKEY_CURRENT_USER/HKEY_LOCAL_MACHINE\n   * @param key\n   * @param valueName\n   * @param wow64  0 for standard registry access (32-bits for 32-bit app, 64-bits for 64-bits app)\n   *               or KEY_WOW64_32KEY to force access to 32-bit registry view,\n   *               or KEY_WOW64_64KEY to force access to 64-bit registry view\n   * @return the value\n   * @throws IllegalArgumentException\n   * @throws IllegalAccessException\n   * @throws InvocationTargetException\n   */\n  public static String readString(int hkey, String key, String valueName, int wow64) \n    throws IllegalArgumentException, IllegalAccessException,\n    InvocationTargetException \n  {\n    if (hkey == HKEY_LOCAL_MACHINE) {\n      return readString(systemRoot, hkey, key, valueName, wow64);\n    }\n    else if (hkey == HKEY_CURRENT_USER) {\n      return readString(userRoot, hkey, key, valueName, wow64);\n    }\n    else {\n      throw new IllegalArgumentException("hkey=" + hkey);\n    }\n  }\n\n  /**\n   * Read value(s) and value name(s) form given key \n   * @param hkey  HKEY_CURRENT_USER/HKEY_LOCAL_MACHINE\n   * @param key\n   * @param wow64  0 for standard registry access (32-bits for 32-bit app, 64-bits for 64-bits app)\n   *               or KEY_WOW64_32KEY to force access to 32-bit registry view,\n   *               or KEY_WOW64_64KEY to force access to 64-bit registry view\n   * @return the value name(s) plus the value(s)\n   * @throws IllegalArgumentException\n   * @throws IllegalAccessException\n   * @throws InvocationTargetException\n   */\n  public static Map&lt;String, String&gt; readStringValues(int hkey, String key, int wow64) \n    throws IllegalArgumentException, IllegalAccessException, InvocationTargetException \n  {\n    if (hkey == HKEY_LOCAL_MACHINE) {\n      return readStringValues(systemRoot, hkey, key, wow64);\n    }\n    else if (hkey == HKEY_CURRENT_USER) {\n      return readStringValues(userRoot, hkey, key, wow64);\n    }\n    else {\n      throw new IllegalArgumentException("hkey=" + hkey);\n    }\n  }\n\n  /**\n   * Read the value name(s) from a given key\n   * @param hkey  HKEY_CURRENT_USER/HKEY_LOCAL_MACHINE\n   * @param key\n   * @param wow64  0 for standard registry access (32-bits for 32-bit app, 64-bits for 64-bits app)\n   *               or KEY_WOW64_32KEY to force access to 32-bit registry view,\n   *               or KEY_WOW64_64KEY to force access to 64-bit registry view\n   * @return the value name(s)\n   * @throws IllegalArgumentException\n   * @throws IllegalAccessException\n   * @throws InvocationTargetException\n   */\n  public static List&lt;String&gt; readStringSubKeys(int hkey, String key, int wow64) \n    throws IllegalArgumentException, IllegalAccessException, InvocationTargetException \n  {\n    if (hkey == HKEY_LOCAL_MACHINE) {\n      return readStringSubKeys(systemRoot, hkey, key, wow64);\n    }\n    else if (hkey == HKEY_CURRENT_USER) {\n      return readStringSubKeys(userRoot, hkey, key, wow64);\n    }\n    else {\n      throw new IllegalArgumentException("hkey=" + hkey);\n    }\n  }\n\n  /**\n   * Create a key\n   * @param hkey  HKEY_CURRENT_USER/HKEY_LOCAL_MACHINE\n   * @param key\n   * @throws IllegalArgumentException\n   * @throws IllegalAccessException\n   * @throws InvocationTargetException\n   */\n  public static void createKey(int hkey, String key) \n    throws IllegalArgumentException, IllegalAccessException, InvocationTargetException \n  {\n    int [] ret;\n    if (hkey == HKEY_LOCAL_MACHINE) {\n      ret = createKey(systemRoot, hkey, key);\n      regCloseKey.invoke(systemRoot, new Object[] { new Integer(ret[0]) });\n    }\n    else if (hkey == HKEY_CURRENT_USER) {\n      ret = createKey(userRoot, hkey, key);\n      regCloseKey.invoke(userRoot, new Object[] { new Integer(ret[0]) });\n    }\n    else {\n      throw new IllegalArgumentException("hkey=" + hkey);\n    }\n    if (ret[1] != REG_SUCCESS) {\n      throw new IllegalArgumentException("rc=" + ret[1] + "  key=" + key);\n    }\n  }\n\n  /**\n   * Write a value in a given key/value name\n   * @param hkey\n   * @param key\n   * @param valueName\n   * @param value\n   * @param wow64  0 for standard registry access (32-bits for 32-bit app, 64-bits for 64-bits app)\n   *               or KEY_WOW64_32KEY to force access to 32-bit registry view,\n   *               or KEY_WOW64_64KEY to force access to 64-bit registry view\n   * @throws IllegalArgumentException\n   * @throws IllegalAccessException\n   * @throws InvocationTargetException\n   */\n  public static void writeStringValue\n    (int hkey, String key, String valueName, String value, int wow64) \n    throws IllegalArgumentException, IllegalAccessException, InvocationTargetException \n  {\n    if (hkey == HKEY_LOCAL_MACHINE) {\n      writeStringValue(systemRoot, hkey, key, valueName, value, wow64);\n    }\n    else if (hkey == HKEY_CURRENT_USER) {\n      writeStringValue(userRoot, hkey, key, valueName, value, wow64);\n    }\n    else {\n      throw new IllegalArgumentException("hkey=" + hkey);\n    }\n  }\n\n  /**\n   * Delete a given key\n   * @param hkey\n   * @param key\n   * @throws IllegalArgumentException\n   * @throws IllegalAccessException\n   * @throws InvocationTargetException\n   */\n  public static void deleteKey(int hkey, String key) \n    throws IllegalArgumentException, IllegalAccessException, InvocationTargetException \n  {\n    int rc = -1;\n    if (hkey == HKEY_LOCAL_MACHINE) {\n      rc = deleteKey(systemRoot, hkey, key);\n    }\n    else if (hkey == HKEY_CURRENT_USER) {\n      rc = deleteKey(userRoot, hkey, key);\n    }\n    if (rc != REG_SUCCESS) {\n      throw new IllegalArgumentException("rc=" + rc + "  key=" + key);\n    }\n  }\n\n  /**\n   * delete a value from a given key/value name\n   * @param hkey\n   * @param key\n   * @param value\n   * @param wow64  0 for standard registry access (32-bits for 32-bit app, 64-bits for 64-bits app)\n   *               or KEY_WOW64_32KEY to force access to 32-bit registry view,\n   *               or KEY_WOW64_64KEY to force access to 64-bit registry view\n   * @throws IllegalArgumentException\n   * @throws IllegalAccessException\n   * @throws InvocationTargetException\n   */\n  public static void deleteValue(int hkey, String key, String value, int wow64) \n    throws IllegalArgumentException, IllegalAccessException, InvocationTargetException \n  {\n    int rc = -1;\n    if (hkey == HKEY_LOCAL_MACHINE) {\n      rc = deleteValue(systemRoot, hkey, key, value, wow64);\n    }\n    else if (hkey == HKEY_CURRENT_USER) {\n      rc = deleteValue(userRoot, hkey, key, value, wow64);\n    }\n    if (rc != REG_SUCCESS) {\n      throw new IllegalArgumentException("rc=" + rc + "  key=" + key + "  value=" + value);\n    }\n  }\n\n  //========================================================================\n  private static int deleteValue(Preferences root, int hkey, String key, String value, int wow64)\n    throws IllegalArgumentException, IllegalAccessException, InvocationTargetException \n  {\n    int[] handles = (int[]) regOpenKey.invoke(root, new Object[] {\n        new Integer(hkey), toCstr(key), new Integer(KEY_ALL_ACCESS | wow64)\n    });\n    if (handles[1] != REG_SUCCESS) {\n      return handles[1];  // can be REG_NOTFOUND, REG_ACCESSDENIED\n    }\n    int rc =((Integer) regDeleteValue.invoke(root, new Object[] { \n          new Integer(handles[0]), toCstr(value) \n          })).intValue();\n    regCloseKey.invoke(root, new Object[] { new Integer(handles[0]) });\n    return rc;\n  }\n\n  //========================================================================\n  private static int deleteKey(Preferences root, int hkey, String key) \n    throws IllegalArgumentException, IllegalAccessException, InvocationTargetException \n  {\n    int rc =((Integer) regDeleteKey.invoke(root, new Object[] {\n        new Integer(hkey), toCstr(key)\n    })).intValue();\n    return rc;  // can REG_NOTFOUND, REG_ACCESSDENIED, REG_SUCCESS\n  }\n\n  //========================================================================\n  private static String readString(Preferences root, int hkey, String key, String value, int wow64)\n    throws IllegalArgumentException, IllegalAccessException, InvocationTargetException \n  {\n    int[] handles = (int[]) regOpenKey.invoke(root, new Object[] {\n        new Integer(hkey), toCstr(key), new Integer(KEY_READ | wow64)\n    });\n    if (handles[1] != REG_SUCCESS) {\n      return null; \n    }\n    byte[] valb = (byte[]) regQueryValueEx.invoke(root, new Object[] {\n        new Integer(handles[0]), toCstr(value)\n    });\n    regCloseKey.invoke(root, new Object[] { new Integer(handles[0]) });\n    return (valb != null ? new String(valb).trim() : null);\n  }\n\n  //========================================================================\n  private static Map&lt;String,String&gt; readStringValues(Preferences root, int hkey, String key, int wow64)\n    throws IllegalArgumentException, IllegalAccessException, InvocationTargetException \n  {\n    HashMap&lt;String, String&gt; results = new HashMap&lt;String,String&gt;();\n    int[] handles = (int[]) regOpenKey.invoke(root, new Object[] {\n        new Integer(hkey), toCstr(key), new Integer(KEY_READ | wow64)\n    });\n    if (handles[1] != REG_SUCCESS) {\n      return null;\n    }\n    int[] info = (int[]) regQueryInfoKey.invoke(root, new Object[] {\n        new Integer(handles[0])\n    });\n\n    int count  = info[2]; // count  \n    int maxlen = info[3]; // value length max\n    for(int index=0; index&lt;count; index++)  {\n      byte[] name = (byte[]) regEnumValue.invoke(root, new Object[] {\n          new Integer(handles[0]), new Integer(index), new Integer(maxlen + 1)\n      });\n      String value = readString(hkey, key, new String(name), wow64);\n      results.put(new String(name).trim(), value);\n    }\n    regCloseKey.invoke(root, new Object[] { new Integer(handles[0]) });\n    return results;\n  }\n\n  //========================================================================\n  private static List&lt;String&gt; readStringSubKeys(Preferences root, int hkey, String key, int wow64)\n    throws IllegalArgumentException, IllegalAccessException, InvocationTargetException \n  {\n    List&lt;String&gt; results = new ArrayList&lt;String&gt;();\n    int[] handles = (int[]) regOpenKey.invoke(root, new Object[] {\n        new Integer(hkey), toCstr(key), new Integer(KEY_READ | wow64) \n        });\n    if (handles[1] != REG_SUCCESS) {\n      return null;\n    }\n    int[] info = (int[]) regQueryInfoKey.invoke(root, new Object[] {\n        new Integer(handles[0])\n    });\n\n    int count  = info[0]; // Fix: info[2] was being used here with wrong results. Suggested by davenpcj, confirmed by Petrucio\n    int maxlen = info[3]; // value length max\n    for(int index=0; index&lt;count; index++)  {\n      byte[] name = (byte[]) regEnumKeyEx.invoke(root, new Object[] {\n          new Integer(handles[0]), new Integer(index), new Integer(maxlen + 1)\n          });\n      results.add(new String(name).trim());\n    }\n    regCloseKey.invoke(root, new Object[] { new Integer(handles[0]) });\n    return results;\n  }\n\n  //========================================================================\n  private static int [] createKey(Preferences root, int hkey, String key)\n    throws IllegalArgumentException, IllegalAccessException, InvocationTargetException \n  {\n    return (int[]) regCreateKeyEx.invoke(root, new Object[] {\n      new Integer(hkey), toCstr(key)\n    });\n  }\n\n  //========================================================================\n  private static void writeStringValue(Preferences root, int hkey, String key, String valueName, String value, int wow64)\n    throws IllegalArgumentException, IllegalAccessException, InvocationTargetException \n  {\n    int[] handles = (int[]) regOpenKey.invoke(root, new Object[] {\n        new Integer(hkey), toCstr(key), new Integer(KEY_ALL_ACCESS | wow64)\n    });\n    regSetValueEx.invoke(root, new Object[] { \n          new Integer(handles[0]), toCstr(valueName), toCstr(value) \n          }); \n    regCloseKey.invoke(root, new Object[] { new Integer(handles[0]) });\n  }\n\n  //========================================================================\n  // utility\n  private static byte[] toCstr(String str) {\n    byte[] result = new byte[str.length() + 1];\n\n    for (int i = 0; i &lt; str.length(); i++) {\n      result[i] = (byte) str.charAt(i);\n    }\n    result[str.length()] = 0;\n    return result;\n  }\n}\n</code></pre>\n'}, {'answer_id': 15689078, 'author': 'Ryan', 'author_id': 656193, 'author_profile': 'https://Stackoverflow.com/users/656193', 'pm_score': 2, 'selected': False, 'text': '<p>Yet another library...</p>\n\n<p><a href="https://code.google.com/p/java-registry/" rel="nofollow">https://code.google.com/p/java-registry/</a></p>\n\n<p>This one launches reg.exe under the covers, reading/writing to temporary files. I didn\'t end up using it, but it looks like a pretty comprehensive implementation. If I did use it, I might dive in and add some better management of the child processes.</p>\n'}, {'answer_id': 17310303, 'author': 'kevinarpe', 'author_id': 257299, 'author_profile': 'https://Stackoverflow.com/users/257299', 'pm_score': 2, 'selected': False, 'text': '<p>My previous edit to @David\'s answer was rejected.  Here is some useful information about it.</p>\n\n<p>This "magic" works because Sun implements the <code>Preferences</code> class for Windows as part of JDK, but it is <a href="http://docs.oracle.com/javase/tutorial/java/javaOO/accesscontrol.html" rel="nofollow">package private</a>.  Parts of the implementation use JNI.</p>\n\n<ul>\n<li>Package private class from JDK <code>java.util.prefs.WindowsPreferences</code>: <a href="http://grepcode.com/file/repository.grepcode.com/java/root/jdk/openjdk/7-b147/java/util/prefs/WindowsPreferences.java" rel="nofollow">http://grepcode.com/file/repository.grepcode.com/java/root/jdk/openjdk/7-b147/java/util/prefs/WindowsPreferences.java</a></li>\n<li>JNI: <a href="http://hg.openjdk.java.net/jdk7/jdk7/jdk/file/9b8c96f96a0f/src/windows/native/java/util/WindowsPreferences.c" rel="nofollow">http://hg.openjdk.java.net/jdk7/jdk7/jdk/file/9b8c96f96a0f/src/windows/native/java/util/WindowsPreferences.c</a></li>\n</ul>\n\n<p>The implementation is selected at runtime using a factory method here: <a href="http://grepcode.com/file/repository.grepcode.com/java/root/jdk/openjdk/7-b147/java/util/prefs/Preferences.java#Preferences.0factory" rel="nofollow">http://grepcode.com/file/repository.grepcode.com/java/root/jdk/openjdk/7-b147/java/util/prefs/Preferences.java#Preferences.0factory</a></p>\n\n<p>The real question: Why doesn\'t OpenJDK expose this API to public?</p>\n'}, {'answer_id': 18103763, 'author': 'TacB0sS', 'author_id': 348189, 'author_profile': 'https://Stackoverflow.com/users/348189', 'pm_score': 0, 'selected': False, 'text': '<p>This was crazy... I took the code from one of the posts here, failed to see there were 18 more comments in which one stated that it does not read a dword value...</p>\n\n<p>In any case, I\'ve refactored the hell of that code into something with less ifs and methods... </p>\n\n<p>The Enum could be refined a bit, but as soon as I\'ve fought my way to read a numeric value or byte array and failed, I\'ve given up...</p>\n\n<p>So here it is:</p>\n\n<pre><code>package com.nu.art.software.utils;\n\n\nimport java.lang.reflect.Method;\nimport java.util.HashMap;\nimport java.util.Map;\nimport java.util.ArrayList;\nimport java.util.List;\nimport java.util.prefs.Preferences;\n\n/**\n *\n * @author TacB0sS\n */\npublic class WinRegistry_TacB0sS {\n\n    public static final class RegistryException\n            extends Exception {\n\n        private static final long serialVersionUID = -8799947496460994651L;\n\n        public RegistryException(String message, Throwable e) {\n            super(message, e);\n        }\n\n        public RegistryException(String message) {\n            super(message);\n        }\n\n\n    }\n\n    public static final int KEY_WOW64_32KEY = 0x0200;\n\n    public static final int KEY_WOW64_64KEY = 0x0100;\n\n    public static final int REG_SUCCESS = 0;\n\n    public static final int REG_NOTFOUND = 2;\n\n    public static final int REG_ACCESSDENIED = 5;\n\n    private static final int KEY_ALL_ACCESS = 0xf003f;\n\n    private static final int KEY_READ = 0x20019;\n\n    public enum WinRegistryKey {\n        User(Preferences.userRoot(), 0x80000001), ;\n\n        // System(Preferences.systemRoot(), 0x80000002);\n\n        private final Preferences preferencesRoot;\n\n        private final Integer key;\n\n        private WinRegistryKey(Preferences preferencesRoot, int key) {\n            this.preferencesRoot = preferencesRoot;\n            this.key = key;\n        }\n    }\n\n    private enum WinRegistryMethod {\n        OpenKey("WindowsRegOpenKey", int.class, byte[].class, int.class) {\n\n            @Override\n            protected void verifyReturnValue(Object retValue)\n                    throws RegistryException {\n                int[] retVal = (int[]) retValue;\n                if (retVal[1] != REG_SUCCESS)\n                    throw new RegistryException("Action Failed, Return Code: " + retVal[1]);\n            }\n        },\n        CreateKeyEx("WindowsRegCreateKeyEx", int.class, byte[].class) {\n\n            @Override\n            protected void verifyReturnValue(Object retValue)\n                    throws RegistryException {\n                int[] retVal = (int[]) retValue;\n                if (retVal[1] != REG_SUCCESS)\n                    throw new RegistryException("Action Failed, Return Code: " + retVal[1]);\n            }\n        },\n        DeleteKey("WindowsRegDeleteKey", int.class, byte[].class) {\n\n            @Override\n            protected void verifyReturnValue(Object retValue)\n                    throws RegistryException {\n                int retVal = ((Integer) retValue).intValue();\n                if (retVal != REG_SUCCESS)\n                    throw new RegistryException("Action Failed, Return Code: " + retVal);\n            }\n        },\n        DeleteValue("WindowsRegDeleteValue", int.class, byte[].class) {\n\n            @Override\n            protected void verifyReturnValue(Object retValue)\n                    throws RegistryException {\n                int retVal = ((Integer) retValue).intValue();\n                if (retVal != REG_SUCCESS)\n                    throw new RegistryException("Action Failed, Return Code: " + retVal);\n            }\n        },\n        CloseKey("WindowsRegCloseKey", int.class),\n        QueryValueEx("WindowsRegQueryValueEx", int.class, byte[].class),\n        EnumKeyEx("WindowsRegEnumKeyEx", int.class, int.class, int.class),\n        EnumValue("WindowsRegEnumValue", int.class, int.class, int.class),\n        QueryInfoKey("WindowsRegQueryInfoKey", int.class),\n        SetValueEx("WindowsRegSetValueEx", int.class, byte[].class, byte[].class);\n\n        private Method method;\n\n        private WinRegistryMethod(String methodName, Class&lt;?&gt;... classes) {\n            // WinRegistryKey.User.preferencesRoot.getClass().getMDeclaredMethods()\n            try {\n                method = WinRegistryKey.User.preferencesRoot.getClass().getDeclaredMethod(methodName, classes);\n            } catch (Exception e) {\n                System.err.println("Error");\n                System.err.println(e);\n            }\n            method.setAccessible(true);\n        }\n\n        public Object invoke(Preferences root, Object... objects)\n                throws RegistryException {\n            Object retValue;\n            try {\n                retValue = method.invoke(root, objects);\n                verifyReturnValue(retValue);\n            } catch (Throwable e) {\n                String params = "";\n                if (objects.length &gt; 0) {\n                    params = objects[0].toString();\n                    for (int i = 1; i &lt; objects.length; i++) {\n                        params += ", " + objects[i];\n                    }\n                }\n                throw new RegistryException("Error invoking method: " + method + ", with params: (" + params + ")", e);\n            }\n            return retValue;\n        }\n\n        protected void verifyReturnValue(Object retValue)\n                throws RegistryException {}\n    }\n\n    private WinRegistry_TacB0sS() {}\n\n    public static String readString(WinRegistryKey regKey, String key, String valueName)\n            throws RegistryException {\n        int retVal = ((int[]) WinRegistryMethod.OpenKey.invoke(regKey.preferencesRoot, regKey.key, toCstr(key),\n                new Integer(KEY_READ)))[0];\n\n        byte[] retValue = (byte[]) WinRegistryMethod.QueryValueEx.invoke(regKey.preferencesRoot, retVal,\n                toCstr(valueName));\n        WinRegistryMethod.CloseKey.invoke(regKey.preferencesRoot, retVal);\n\n        /*\n         * Should this return an Empty String.\n         */\n        return (retValue != null ? new String(retValue).trim() : null);\n    }\n\n    public static Map&lt;String, String&gt; readStringValues(WinRegistryKey regKey, String key)\n            throws RegistryException {\n        HashMap&lt;String, String&gt; results = new HashMap&lt;String, String&gt;();\n        int retVal = ((int[]) WinRegistryMethod.OpenKey.invoke(regKey.preferencesRoot, regKey.key, toCstr(key),\n                new Integer(KEY_READ)))[0];\n\n        int[] info = (int[]) WinRegistryMethod.QueryInfoKey.invoke(regKey.preferencesRoot, retVal);\n\n        int count = info[2]; // count\n        int maxlen = info[3]; // value length max\n        for (int index = 0; index &lt; count; index++) {\n            byte[] name = (byte[]) WinRegistryMethod.EnumValue.invoke(regKey.preferencesRoot, retVal,\n                    new Integer(index), new Integer(maxlen + 1));\n            String value = readString(regKey, key, new String(name));\n            results.put(new String(name).trim(), value);\n        }\n\n        WinRegistryMethod.CloseKey.invoke(regKey.preferencesRoot, retVal);\n        return results;\n    }\n\n    public static List&lt;String&gt; readStringSubKeys(WinRegistryKey regKey, String key)\n            throws RegistryException {\n        List&lt;String&gt; results = new ArrayList&lt;String&gt;();\n        int retVal = ((int[]) WinRegistryMethod.OpenKey.invoke(regKey.preferencesRoot, regKey.key, toCstr(key),\n                new Integer(KEY_READ)))[0];\n\n        int[] info = (int[]) WinRegistryMethod.QueryInfoKey.invoke(regKey.preferencesRoot, retVal);\n\n        int count = info[0]; // Fix: info[2] was being used here with wrong results. Suggested by davenpcj, confirmed by\n                                // Petrucio\n        int maxlen = info[3]; // value length max\n        for (int index = 0; index &lt; count; index++) {\n            byte[] name = (byte[]) WinRegistryMethod.EnumValue.invoke(regKey.preferencesRoot, retVal,\n                    new Integer(index), new Integer(maxlen + 1));\n            results.add(new String(name).trim());\n        }\n\n        WinRegistryMethod.CloseKey.invoke(regKey.preferencesRoot, retVal);\n        return results;\n    }\n\n    public static void createKey(WinRegistryKey regKey, String key)\n            throws RegistryException {\n        int[] retVal = (int[]) WinRegistryMethod.CreateKeyEx.invoke(regKey.preferencesRoot, regKey.key, toCstr(key));\n        WinRegistryMethod.CloseKey.invoke(regKey.preferencesRoot, retVal[0]);\n    }\n\n    public static void writeStringValue(WinRegistryKey regKey, String key, String valueName, String value)\n            throws RegistryException {\n        int retVal = ((int[]) WinRegistryMethod.OpenKey.invoke(regKey.preferencesRoot, regKey.key, toCstr(key),\n                new Integer(KEY_ALL_ACCESS)))[0];\n\n        WinRegistryMethod.SetValueEx.invoke(regKey.preferencesRoot, retVal, toCstr(valueName), toCstr(value));\n        WinRegistryMethod.CloseKey.invoke(regKey.preferencesRoot, retVal);\n    }\n\n    public static void deleteKey(WinRegistryKey regKey, String key)\n            throws RegistryException {\n        WinRegistryMethod.DeleteKey.invoke(regKey.preferencesRoot, regKey.key, toCstr(key));\n    }\n\n    public static void deleteValue(WinRegistryKey regKey, String key, String value)\n            throws RegistryException {\n        int retVal = ((int[]) WinRegistryMethod.OpenKey.invoke(regKey.preferencesRoot, regKey.key, toCstr(key),\n                new Integer(KEY_ALL_ACCESS)))[0];\n        WinRegistryMethod.DeleteValue.invoke(regKey.preferencesRoot, retVal, toCstr(value));\n        WinRegistryMethod.CloseKey.invoke(regKey.preferencesRoot, retVal);\n    }\n\n    // utility\n    private static byte[] toCstr(String str) {\n        byte[] result = new byte[str.length() + 1];\n\n        for (int i = 0; i &lt; str.length(); i++) {\n            result[i] = (byte) str.charAt(i);\n        }\n        result[str.length()] = \'\\0\';\n        return result;\n    }\n}\n</code></pre>\n\n<p><strong>NOTE: THIS DOES NOT READ ANYTHING ELSE BUT STRINGS!!!!!</strong></p>\n'}, {'answer_id': 22589715, 'author': 'Ernestas Gruodis', 'author_id': 2111085, 'author_profile': 'https://Stackoverflow.com/users/2111085', 'pm_score': -1, 'selected': False, 'text': '<p>In response to David <a href="https://stackoverflow.com/a/6163701/2111085">answer</a> - I would do some enhancements:</p>\n\n<pre><code>import java.lang.reflect.InvocationTargetException;\nimport java.lang.reflect.Method;\nimport java.util.ArrayList;\nimport java.util.HashMap;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.logging.Level;\nimport java.util.logging.Logger;\nimport java.util.prefs.Preferences;\n\npublic class WinRegistry {\n\n    public static final int HKEY_CURRENT_USER = 0x80000001,\n            HKEY_LOCAL_MACHINE = 0x80000002,\n            REG_SUCCESS = 0,\n            REG_NOTFOUND = 2,\n            REG_ACCESSDENIED = 5,\n            KEY_ALL_ACCESS = 0xf003f,\n            KEY_READ = 0x20019;\n    private static final Preferences userRoot = Preferences.userRoot(),\n            systemRoot = Preferences.systemRoot();\n    private static final Class&lt;? extends Preferences&gt; userClass = userRoot.getClass();\n    private static Method regOpenKey,\n            regCloseKey,\n            regQueryValueEx,\n            regEnumValue,\n            regQueryInfoKey,\n            regEnumKeyEx,\n            regCreateKeyEx,\n            regSetValueEx,\n            regDeleteKey,\n            regDeleteValue;\n\n    static {\n        try {\n            (regOpenKey = userClass.getDeclaredMethod("WindowsRegOpenKey", new Class[]{int.class, byte[].class, int.class})).setAccessible(true);\n            (regCloseKey = userClass.getDeclaredMethod("WindowsRegCloseKey", new Class[]{int.class})).setAccessible(true);\n            (regQueryValueEx = userClass.getDeclaredMethod("WindowsRegQueryValueEx", new Class[]{int.class, byte[].class})).setAccessible(true);\n            (regEnumValue = userClass.getDeclaredMethod("WindowsRegEnumValue", new Class[]{int.class, int.class, int.class})).setAccessible(true);\n            (regQueryInfoKey = userClass.getDeclaredMethod("WindowsRegQueryInfoKey1", new Class[]{int.class})).setAccessible(true);\n            (regEnumKeyEx = userClass.getDeclaredMethod("WindowsRegEnumKeyEx", new Class[]{int.class, int.class, int.class})).setAccessible(true);\n            (regCreateKeyEx = userClass.getDeclaredMethod("WindowsRegCreateKeyEx", new Class[]{int.class, byte[].class})).setAccessible(true);\n            (regSetValueEx = userClass.getDeclaredMethod("WindowsRegSetValueEx", new Class[]{int.class, byte[].class, byte[].class})).setAccessible(true);\n            (regDeleteValue = userClass.getDeclaredMethod("WindowsRegDeleteValue", new Class[]{int.class, byte[].class})).setAccessible(true);\n            (regDeleteKey = userClass.getDeclaredMethod("WindowsRegDeleteKey", new Class[]{int.class, byte[].class})).setAccessible(true);\n        } catch (NoSuchMethodException | SecurityException ex) {\n            Logger.getLogger(WinRegistry.class.getName()).log(Level.SEVERE, null, ex);\n        }\n    }\n\n    /**\n     * Read a value from key and value name\n     *\n     * @param hkey HKEY_CURRENT_USER/HKEY_LOCAL_MACHINE\n     * @param key\n     * @param valueName\n     * @return the value\n     * @throws IllegalArgumentException\n     * @throws IllegalAccessException\n     * @throws InvocationTargetException\n     */\n    public static String readString(int hkey, String key, String valueName) throws IllegalArgumentException, IllegalAccessException, InvocationTargetException {\n\n        switch (hkey) {\n            case HKEY_LOCAL_MACHINE:\n                return readString(systemRoot, hkey, key, valueName);\n            case HKEY_CURRENT_USER:\n                return readString(userRoot, hkey, key, valueName);\n            default:\n                throw new IllegalArgumentException("hkey=" + hkey);\n        }\n    }\n\n    /**\n     * Read value(s) and value name(s) form given key\n     *\n     * @param hkey HKEY_CURRENT_USER/HKEY_LOCAL_MACHINE\n     * @param key\n     * @return the value name(s) plus the value(s)\n     * @throws IllegalArgumentException\n     * @throws IllegalAccessException\n     * @throws InvocationTargetException\n     */\n    public static Map&lt;String, String&gt; readStringValues(int hkey, String key) throws IllegalArgumentException, IllegalAccessException, InvocationTargetException {\n\n        switch (hkey) {\n            case HKEY_LOCAL_MACHINE:\n                return readStringValues(systemRoot, hkey, key);\n            case HKEY_CURRENT_USER:\n                return readStringValues(userRoot, hkey, key);\n            default:\n                throw new IllegalArgumentException("hkey=" + hkey);\n        }\n    }\n\n    /**\n     * Read the value name(s) from a given key\n     *\n     * @param hkey HKEY_CURRENT_USER/HKEY_LOCAL_MACHINE\n     * @param key\n     * @return the value name(s)\n     * @throws IllegalArgumentException\n     * @throws IllegalAccessException\n     * @throws InvocationTargetException\n     */\n    public static List&lt;String&gt; readStringSubKeys(int hkey, String key) throws IllegalArgumentException, IllegalAccessException, InvocationTargetException {\n\n        switch (hkey) {\n            case HKEY_LOCAL_MACHINE:\n                return readStringSubKeys(systemRoot, hkey, key);\n            case HKEY_CURRENT_USER:\n                return readStringSubKeys(userRoot, hkey, key);\n            default:\n                throw new IllegalArgumentException("hkey=" + hkey);\n        }\n    }\n\n    /**\n     * Create a key\n     *\n     * @param hkey HKEY_CURRENT_USER/HKEY_LOCAL_MACHINE\n     * @param key\n     * @throws IllegalArgumentException\n     * @throws IllegalAccessException\n     * @throws InvocationTargetException\n     */\n    public static void createKey(int hkey, String key) throws IllegalArgumentException, IllegalAccessException, InvocationTargetException {\n\n        int[] ret;\n        switch (hkey) {\n            case HKEY_LOCAL_MACHINE:\n                ret = createKey(systemRoot, hkey, key);\n                regCloseKey.invoke(systemRoot, new Object[]{ret[0]});\n                break;\n            case HKEY_CURRENT_USER:\n                ret = createKey(userRoot, hkey, key);\n                regCloseKey.invoke(userRoot, new Object[]{ret[0]});\n                break;\n            default:\n                throw new IllegalArgumentException("hkey=" + hkey);\n        }\n\n        if (ret[1] != REG_SUCCESS) {\n            throw new IllegalArgumentException("rc=" + ret[1] + " key=" + key);\n        }\n    }\n\n    /**\n     * Write a value in a given key/value name\n     *\n     * @param hkey\n     * @param key\n     * @param valueName\n     * @param value\n     * @throws IllegalArgumentException\n     * @throws IllegalAccessException\n     * @throws InvocationTargetException\n     */\n    public static void writeStringValue(int hkey, String key, String valueName, String value) throws IllegalArgumentException, IllegalAccessException, InvocationTargetException {\n\n        switch (hkey) {\n            case HKEY_LOCAL_MACHINE:\n                writeStringValue(systemRoot, hkey, key, valueName, value);\n                break;\n            case HKEY_CURRENT_USER:\n                writeStringValue(userRoot, hkey, key, valueName, value);\n                break;\n            default:\n                throw new IllegalArgumentException("hkey=" + hkey);\n        }\n    }\n\n    /**\n     * Delete a given key\n     *\n     * @param hkey\n     * @param key\n     * @throws IllegalArgumentException\n     * @throws IllegalAccessException\n     * @throws InvocationTargetException\n     */\n    public static void deleteKey(int hkey, String key) throws IllegalArgumentException, IllegalAccessException, InvocationTargetException {\n\n        int rc = -1;\n        switch (hkey) {\n            case HKEY_LOCAL_MACHINE:\n                rc = deleteKey(systemRoot, hkey, key);\n                break;\n            case HKEY_CURRENT_USER:\n                rc = deleteKey(userRoot, hkey, key);\n        }\n\n        if (rc != REG_SUCCESS) {\n            throw new IllegalArgumentException("rc=" + rc + " key=" + key);\n        }\n    }\n\n    /**\n     * delete a value from a given key/value name\n     *\n     * @param hkey\n     * @param key\n     * @param value\n     * @throws IllegalArgumentException\n     * @throws IllegalAccessException\n     * @throws InvocationTargetException\n     */\n    public static void deleteValue(int hkey, String key, String value) throws IllegalArgumentException, IllegalAccessException, InvocationTargetException {\n\n        int rc = -1;\n        switch (hkey) {\n            case HKEY_LOCAL_MACHINE:\n                rc = deleteValue(systemRoot, hkey, key, value);\n                break;\n            case HKEY_CURRENT_USER:\n                rc = deleteValue(userRoot, hkey, key, value);\n        }\n\n        if (rc != REG_SUCCESS) {\n            throw new IllegalArgumentException("rc=" + rc + " key=" + key + " value=" + value);\n        }\n    }\n\n    private static int deleteValue(Preferences root, int hkey, String key, String value) throws IllegalArgumentException, IllegalAccessException, InvocationTargetException {\n\n        int[] handles = (int[]) regOpenKey.invoke(root, new Object[]{hkey, toCstr(key), KEY_ALL_ACCESS});\n        if (handles[1] != REG_SUCCESS) {\n            return handles[1];//Can be REG_NOTFOUND, REG_ACCESSDENIED\n        }\n        int rc = ((Integer) regDeleteValue.invoke(root, new Object[]{handles[0], toCstr(value)}));\n        regCloseKey.invoke(root, new Object[]{handles[0]});\n        return rc;\n    }\n\n    private static int deleteKey(Preferences root, int hkey, String key) throws IllegalArgumentException, IllegalAccessException, InvocationTargetException {\n\n        int rc = ((Integer) regDeleteKey.invoke(root, new Object[]{hkey, toCstr(key)}));\n        return rc;  //Can be REG_NOTFOUND, REG_ACCESSDENIED, REG_SUCCESS\n    }\n\n    private static String readString(Preferences root, int hkey, String key, String value) throws IllegalArgumentException, IllegalAccessException, InvocationTargetException {\n\n        int[] handles = (int[]) regOpenKey.invoke(root, new Object[]{hkey, toCstr(key), KEY_READ});\n        if (handles[1] != REG_SUCCESS) {\n            return null;\n        }\n        byte[] valb = (byte[]) regQueryValueEx.invoke(root, new Object[]{handles[0], toCstr(value)});\n        regCloseKey.invoke(root, new Object[]{handles[0]});\n        return (valb != null ? new String(valb).trim() : null);\n    }\n\n    private static Map&lt;String, String&gt; readStringValues(Preferences root, int hkey, String key) throws IllegalArgumentException, IllegalAccessException, InvocationTargetException {\n\n        HashMap&lt;String, String&gt; results = new HashMap&lt;&gt;();\n        int[] handles = (int[]) regOpenKey.invoke(root, new Object[]{hkey, toCstr(key), KEY_READ});\n        if (handles[1] != REG_SUCCESS) {\n            return null;\n        }\n        int[] info = (int[]) regQueryInfoKey.invoke(root, new Object[]{handles[0]});\n\n        int count = info[0]; //Count  \n        int maxlen = info[3]; //Max value length\n        for (int index = 0; index &lt; count; index++) {\n            byte[] name = (byte[]) regEnumValue.invoke(root, new Object[]{handles[0], index, maxlen + 1});\n            String value = readString(hkey, key, new String(name));\n            results.put(new String(name).trim(), value);\n        }\n        regCloseKey.invoke(root, new Object[]{handles[0]});\n        return results;\n    }\n\n    private static List&lt;String&gt; readStringSubKeys(Preferences root, int hkey, String key) throws IllegalArgumentException, IllegalAccessException, InvocationTargetException {\n\n        List&lt;String&gt; results = new ArrayList&lt;&gt;();\n        int[] handles = (int[]) regOpenKey.invoke(root, new Object[]{hkey, toCstr(key), KEY_READ});\n        if (handles[1] != REG_SUCCESS) {\n            return null;\n        }\n        int[] info = (int[]) regQueryInfoKey.invoke(root, new Object[]{handles[0]});\n\n        int count = info[0];//Count\n        int maxlen = info[3]; //Max value length\n        for (int index = 0; index &lt; count; index++) {\n            byte[] name = (byte[]) regEnumKeyEx.invoke(root, new Object[]{handles[0], index, maxlen + 1});\n            results.add(new String(name).trim());\n        }\n        regCloseKey.invoke(root, new Object[]{handles[0]});\n        return results;\n    }\n\n    private static int[] createKey(Preferences root, int hkey, String key) throws IllegalArgumentException, IllegalAccessException, InvocationTargetException {\n\n        return (int[]) regCreateKeyEx.invoke(root, new Object[]{hkey, toCstr(key)});\n    }\n\n    private static void writeStringValue(Preferences root, int hkey, String key, String valueName, String value) throws IllegalArgumentException, IllegalAccessException, InvocationTargetException {\n\n        int[] handles = (int[]) regOpenKey.invoke(root, new Object[]{hkey, toCstr(key), KEY_ALL_ACCESS});\n        regSetValueEx.invoke(root, new Object[]{handles[0], toCstr(valueName), toCstr(value)});\n        regCloseKey.invoke(root, new Object[]{handles[0]});\n    }\n\n    private static byte[] toCstr(String str) {\n\n        byte[] result = new byte[str.length() + 1];\n        for (int i = 0; i &lt; str.length(); i++) {\n            result[i] = (byte) str.charAt(i);\n        }\n        result[str.length()] = 0;\n        return result;\n    }\n}\n</code></pre>\n'}, {'answer_id': 24877559, 'author': 'Boann', 'author_id': 964243, 'author_profile': 'https://Stackoverflow.com/users/964243', 'pm_score': 0, 'selected': False, 'text': '<p>This uses the same Java internal APIs as in <a href="https://stackoverflow.com/a/6163701">in David\'s answer</a>, but I\'ve rewritten it completely. It\'s shorter now and nicer to use. I also added support for HKEY_CLASSES_ROOT and other hives. It still has some of the other limitations though (such as no DWORD support and no Unicode support) which are due to the underlying API and are sadly unavoidable with this approach. Still, if you only need basic string reading/writing and don\'t want to load a native DLL, it\'s handy.</p>\n\n<p>I\'m sure you can figure out how to use it.</p>\n\n<p>Public domain. Have fun.</p>\n\n<pre><code>import java.util.*;\nimport java.lang.reflect.Method;\n\n/**\n * Simple registry access class implemented using some private APIs\n * in java.util.prefs. It has no other prerequisites.\n */\npublic final class WindowsRegistry {\n    /**\n     * Tells if the Windows registry functions are available.\n     * (They will not be available when not running on Windows, for example.)\n     */\n    public static boolean isAvailable() {\n        return initError == null;\n    }\n\n\n\n    /** Reads a string value from the given key and value name. */\n    public static String readValue(String keyName, String valueName) {\n        try (Key key = Key.open(keyName, KEY_READ)) {\n            return fromByteArray(invoke(regQueryValueEx, key.handle, toByteArray(valueName)));\n        }\n    }\n\n\n\n    /** Returns a map of all the name-value pairs in the given key. */\n    public static Map&lt;String,String&gt; readValues(String keyName) {\n        try (Key key = Key.open(keyName, KEY_READ)) {\n            int[] info = invoke(regQueryInfoKey, key.handle);\n            checkError(info[INFO_ERROR_CODE]);\n            int count = info[INFO_COUNT_VALUES];\n            int maxlen = info[INFO_MAX_VALUE_LENGTH] + 1;\n            Map&lt;String,String&gt; values = new HashMap&lt;&gt;();\n            for (int i = 0; i &lt; count; i++) {\n                String valueName = fromByteArray(invoke(regEnumValue, key.handle, i, maxlen));\n                values.put(valueName, readValue(keyName, valueName));\n            }\n            return values;\n        }\n    }\n\n\n\n    /** Returns a list of the names of all the subkeys of a key. */\n    public static List&lt;String&gt; readSubkeys(String keyName) {\n        try (Key key = Key.open(keyName, KEY_READ)) {\n            int[] info = invoke(regQueryInfoKey, key.handle);\n            checkError(info[INFO_ERROR_CODE]);\n            int count = info[INFO_COUNT_KEYS];\n            int maxlen = info[INFO_MAX_KEY_LENGTH] + 1;\n            List&lt;String&gt; subkeys = new ArrayList&lt;&gt;(count);\n            for (int i = 0; i &lt; count; i++) {\n                subkeys.add(fromByteArray(invoke(regEnumKeyEx, key.handle, i, maxlen)));\n            }\n            return subkeys;\n        }\n    }\n\n\n\n    /** Writes a string value with a given key and value name. */\n    public static void writeValue(String keyName, String valueName, String value) {\n        try (Key key = Key.open(keyName, KEY_WRITE)) {\n            checkError(invoke(regSetValueEx, key.handle, toByteArray(valueName), toByteArray(value)));\n        }\n    }\n\n\n\n    /** Deletes a value within a key. */\n    public static void deleteValue(String keyName, String valueName) {\n        try (Key key = Key.open(keyName, KEY_WRITE)) {\n            checkError(invoke(regDeleteValue, key.handle, toByteArray(valueName)));\n        }\n    }\n\n\n\n    /**\n     * Deletes a key and all values within it. If the key has subkeys, an\n     * "Access denied" error will be thrown. Subkeys must be deleted separately.\n     */\n    public static void deleteKey(String keyName) {\n        checkError(invoke(regDeleteKey, keyParts(keyName)));\n    }\n\n\n\n    /**\n     * Creates a key. Parent keys in the path will also be created if necessary.\n     * This method returns without error if the key already exists.\n     */\n    public static void createKey(String keyName) {\n        int[] info = invoke(regCreateKeyEx, keyParts(keyName));\n        checkError(info[INFO_ERROR_CODE]);\n        invoke(regCloseKey, info[INFO_HANDLE]);\n    }\n\n\n\n    /**\n     * The exception type that will be thrown if a registry operation fails.\n     */\n    public static class RegError extends RuntimeException {\n        public RegError(String message, Throwable cause) {\n            super(message, cause);\n        }\n    }\n\n\n\n\n\n    // *************\n    // PRIVATE STUFF\n    // *************\n\n    private WindowsRegistry() {}\n\n\n    // Map of registry hive names to constants from winreg.h\n    private static final Map&lt;String,Integer&gt; hives = new HashMap&lt;&gt;();\n    static {\n        hives.put("HKEY_CLASSES_ROOT",   0x80000000); hives.put("HKCR", 0x80000000);\n        hives.put("HKEY_CURRENT_USER",   0x80000001); hives.put("HKCU", 0x80000001);\n        hives.put("HKEY_LOCAL_MACHINE",  0x80000002); hives.put("HKLM", 0x80000002);\n        hives.put("HKEY_USERS",          0x80000003); hives.put("HKU",  0x80000003);\n        hives.put("HKEY_CURRENT_CONFIG", 0x80000005); hives.put("HKCC", 0x80000005);\n    }\n\n\n    // Splits a path such as HKEY_LOCAL_MACHINE\\Software\\Microsoft into a pair of\n    // values used by the underlying API: An integer hive constant and a byte array\n    // of the key path within that hive.\n    private static Object[] keyParts(String fullKeyName) {\n        int x = fullKeyName.indexOf(\'\\\\\');\n        String hiveName = x &gt;= 0 ? fullKeyName.substring(0, x)  : fullKeyName;\n        String keyName  = x &gt;= 0 ? fullKeyName.substring(x + 1) : "";\n        Integer hkey = hives.get(hiveName);\n        if (hkey == null) throw new RegError("Unknown registry hive: " + hiveName, null);\n        return new Object[] { hkey, toByteArray(keyName) };\n    }\n\n\n    // Type encapsulating a native handle to a registry key\n    private static class Key implements AutoCloseable {\n        final int handle;\n\n        private Key(int handle) {\n            this.handle = handle;\n        }\n\n        static Key open(String keyName, int accessMode) {\n            Object[] keyParts = keyParts(keyName);\n            int[] ret = invoke(regOpenKey, keyParts[0], keyParts[1], accessMode);\n            checkError(ret[INFO_ERROR_CODE]);\n            return new Key(ret[INFO_HANDLE]);\n        }\n\n        @Override\n        public void close() {\n            invoke(regCloseKey, handle);\n        }\n    }\n\n\n    // Array index constants for results of regOpenKey, regCreateKeyEx, and regQueryInfoKey\n    private static final int\n        INFO_HANDLE = 0,\n        INFO_COUNT_KEYS = 0,\n        INFO_ERROR_CODE = 1,\n        INFO_COUNT_VALUES = 2,\n        INFO_MAX_KEY_LENGTH = 3,\n        INFO_MAX_VALUE_LENGTH = 4;\n\n\n    // Registry access mode constants from winnt.h\n    private static final int\n        KEY_READ = 0x20019,\n        KEY_WRITE = 0x20006;\n\n\n    // Error constants from winerror.h\n    private static final int\n        ERROR_SUCCESS = 0,\n        ERROR_FILE_NOT_FOUND = 2,\n        ERROR_ACCESS_DENIED = 5;\n\n    private static void checkError(int e) {\n        if (e == ERROR_SUCCESS) return;\n        throw new RegError(\n            e == ERROR_FILE_NOT_FOUND ? "Key not found" :\n            e == ERROR_ACCESS_DENIED ? "Access denied" :\n            ("Error number " + e), null);\n    }\n\n\n    // Registry access methods in java.util.prefs.WindowsPreferences\n    private static final Method\n        regOpenKey = getMethod("WindowsRegOpenKey", int.class, byte[].class, int.class),\n        regCloseKey = getMethod("WindowsRegCloseKey", int.class),\n        regQueryValueEx = getMethod("WindowsRegQueryValueEx", int.class, byte[].class),\n        regQueryInfoKey = getMethod("WindowsRegQueryInfoKey", int.class),\n        regEnumValue = getMethod("WindowsRegEnumValue", int.class, int.class, int.class),\n        regEnumKeyEx = getMethod("WindowsRegEnumKeyEx", int.class, int.class, int.class),\n        regSetValueEx = getMethod("WindowsRegSetValueEx", int.class, byte[].class, byte[].class),\n        regDeleteValue = getMethod("WindowsRegDeleteValue", int.class, byte[].class),\n        regDeleteKey = getMethod("WindowsRegDeleteKey", int.class, byte[].class),\n        regCreateKeyEx = getMethod("WindowsRegCreateKeyEx", int.class, byte[].class);\n\n    private static Throwable initError;\n\n    private static Method getMethod(String methodName, Class&lt;?&gt;... parameterTypes) {\n        try {\n            Method m = java.util.prefs.Preferences.systemRoot().getClass()\n                .getDeclaredMethod(methodName, parameterTypes);\n            m.setAccessible(true);\n            return m;\n        } catch (Throwable t) {\n            initError = t;\n            return null;\n        }\n    }\n\n    @SuppressWarnings("unchecked")\n    private static &lt;T&gt; T invoke(Method method, Object... args) {\n        if (initError != null)\n            throw new RegError("Registry methods are not available", initError);\n        try {\n            return (T)method.invoke(null, args);\n        } catch (Exception e) {\n            throw new RegError(null, e);\n        }\n    }\n\n\n    // Conversion of strings to/from null-terminated byte arrays.\n    // There is no support for Unicode; sorry, this is a limitation\n    // of the underlying methods that Java makes available.\n    private static byte[] toByteArray(String str) {\n        byte[] bytes = new byte[str.length() + 1];\n        for (int i = 0; i &lt; str.length(); i++)\n            bytes[i] = (byte)str.charAt(i);\n        return bytes;\n    }\n\n    private static String fromByteArray(byte[] bytes) {\n        if (bytes == null) return null;\n        char[] chars = new char[bytes.length - 1];\n        for (int i = 0; i &lt; chars.length; i++)\n            chars[i] = (char)((int)bytes[i] &amp; 0xFF);\n        return new String(chars);\n    }\n}\n</code></pre>\n\n<p>One day, Java will have a built-in <a href="http://openjdk.java.net/jeps/191" rel="nofollow">foreign function interface</a> for easy access to native APIs, and this sort of hack will be unnecessary.</p>\n'}, {'answer_id': 26097666, 'author': 'Vipul Paralikar', 'author_id': 1677308, 'author_profile': 'https://Stackoverflow.com/users/1677308', 'pm_score': 2, 'selected': False, 'text': '<p>The <code>java.util.prefs</code> package provides a way for applications to store and retrieve user and system preferences and data configuration. These preference data will be stored persistently in an implementation-dependent backing stored. For example in Windows operating system in will stored in Windows registry.</p>\n\n<p>To write and read these data we use the <code>java.util.prefs.Preferences</code> class. Below code shows how to read and write to the <code>HKCU</code> and <code>HKLM</code> in the registry.</p>\n\n<pre><code>import java.util.prefs.Preferences;\n\npublic class RegistryDemo {\n    public static final String PREF_KEY = "org.username";\n    public static void main(String[] args) {\n        //\n        // Write Preferences information to HKCU (HKEY_CURRENT_USER),\n        // HKCU\\Software\\JavaSoft\\Prefs\\org.username\n        //\n        Preferences userPref = Preferences.userRoot();\n        userPref.put(PREF_KEY, "xyz");\n\n        //\n        // Below we read back the value we\'ve written in the code above.\n        //\n        System.out.println("Preferences = "\n                + userPref.get(PREF_KEY, PREF_KEY + " was not found."));\n\n        //\n        // Write Preferences information to HKLM (HKEY_LOCAL_MACHINE),\n        // HKLM\\Software\\JavaSoft\\Prefs\\org.username\n        //\n        Preferences systemPref = Preferences.systemRoot();\n        systemPref.put(PREF_KEY, "xyz");\n\n        //\n        // Read back the value we\'ve written in the code above.\n        //\n        System.out.println("Preferences = "\n                + systemPref.get(PREF_KEY, PREF_KEY + " was not found."));\n    }\n}\n</code></pre>\n'}, {'answer_id': 26106387, 'author': 'Palak Nagar', 'author_id': 4092109, 'author_profile': 'https://Stackoverflow.com/users/4092109', 'pm_score': -1, 'selected': False, 'text': '<p>You can execute these "REG QUERY" command using <strong>java</strong> code.</p>\n\n<p>Try to execute this from command prompt and execute command from java code.</p>\n\n<blockquote>\n  <p>HKEY_LOCAL_MACHINE "SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion"</p>\n</blockquote>\n\n<p>To Search details like productname version etc.. use /v amd "name". </p>\n\n<blockquote>\n  <p>HKEY_LOCAL_MACHINE "SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion" /v "ProductName"</p>\n</blockquote>\n'}, {'answer_id': 30019357, 'author': 'BullyWiiPlaza', 'author_id': 3764804, 'author_profile': 'https://Stackoverflow.com/users/3764804', 'pm_score': 3, 'selected': False, 'text': '<p>The best way to write to the register probably is using the <code>reg import</code> native Windows command and giving it the file path to the <code>.reg</code> file which has been generated by exporting something from the registry.</p>\n\n<p>Reading is done with the <code>reg query</code> command. Also see the documentation:\n<a href="https://technet.microsoft.com/en-us/library/cc742028.aspx" rel="noreferrer">https://technet.microsoft.com/en-us/library/cc742028.aspx</a></p>\n\n<p>Therefore the following code should be self-explanatory:</p>\n\n<pre><code>import java.io.BufferedReader;\nimport java.io.File;\nimport java.io.FileNotFoundException;\nimport java.io.IOException;\nimport java.io.InputStreamReader;\n\npublic class WindowsRegistry\n{\n    public static void importSilently(String regFilePath) throws IOException,\n            InterruptedException\n    {\n        if (!new File(regFilePath).exists())\n        {\n            throw new FileNotFoundException();\n        }\n\n        Process importer = Runtime.getRuntime().exec("reg import " + regFilePath);\n\n        importer.waitFor();\n    }\n\n    public static void overwriteValue(String keyPath, String keyName,\n            String keyValue) throws IOException, InterruptedException\n    {\n        Process overwriter = Runtime.getRuntime().exec(\n                "reg add " + keyPath + " /t REG_SZ /v \\"" + keyName + "\\" /d "\n                        + keyValue + " /f");\n\n        overwriter.waitFor();\n    }\n\n    public static String getValue(String keyPath, String keyName)\n            throws IOException, InterruptedException\n    {\n        Process keyReader = Runtime.getRuntime().exec(\n                "reg query \\"" + keyPath + "\\" /v \\"" + keyName + "\\"");\n\n        BufferedReader outputReader;\n        String readLine;\n        StringBuffer outputBuffer = new StringBuffer();\n\n        outputReader = new BufferedReader(new InputStreamReader(\n                keyReader.getInputStream()));\n\n        while ((readLine = outputReader.readLine()) != null)\n        {\n            outputBuffer.append(readLine);\n        }\n\n        String[] outputComponents = outputBuffer.toString().split("    ");\n\n        keyReader.waitFor();\n\n        return outputComponents[outputComponents.length - 1];\n    }\n}\n</code></pre>\n'}, {'answer_id': 35532028, 'author': 'pratapvaibhav19', 'author_id': 4585099, 'author_profile': 'https://Stackoverflow.com/users/4585099', 'pm_score': 3, 'selected': False, 'text': '<p>Thanks to original post. I have reskinned this utility class and come up over the flaws which it had earlier, thought it might help others so posting here. I have also added some extra utility methods. Now it is able to read any file in windows registry(including REG_DWORD, REG_BINARY, REG_EXPAND_SZ etc.). All the methods work like a charm. Just copy and paste it and it should work. Here is the reskinned and modified class:  </p>\n\n<pre><code>import java.io.BufferedReader;\nimport java.io.IOException;\nimport java.io.InputStreamReader;\nimport java.lang.reflect.InvocationTargetException;\nimport java.lang.reflect.Method;\nimport java.util.HashMap;\nimport java.util.Map;\nimport java.util.ArrayList;\nimport java.util.List;\nimport java.util.StringTokenizer;\nimport java.util.prefs.Preferences;\n\npublic class WinRegistry {\n\n    private static final int REG_SUCCESS = 0;\n    private static final int REG_NOTFOUND = 2;\n    private static final int KEY_READ = 0x20019;\n    private static final int REG_ACCESSDENIED = 5;\n    private static final int KEY_ALL_ACCESS = 0xf003f;\n    public static final int HKEY_CLASSES_ROOT = 0x80000000;\n    public static final int HKEY_CURRENT_USER = 0x80000001;\n    public static final int HKEY_LOCAL_MACHINE = 0x80000002;\n    private static final String CLASSES_ROOT = "HKEY_CLASSES_ROOT";\n    private static final String CURRENT_USER = "HKEY_CURRENT_USER";\n    private static final String LOCAL_MACHINE = "HKEY_LOCAL_MACHINE";\n    private static Preferences userRoot = Preferences.userRoot();\n    private static Preferences systemRoot = Preferences.systemRoot();\n    private static Class&lt;? extends Preferences&gt; userClass = userRoot.getClass();\n    private static Method regOpenKey = null;\n    private static Method regCloseKey = null;\n    private static Method regQueryValueEx = null;\n    private static Method regEnumValue = null;\n    private static Method regQueryInfoKey = null;\n    private static Method regEnumKeyEx = null;\n    private static Method regCreateKeyEx = null;\n    private static Method regSetValueEx = null;\n    private static Method regDeleteKey = null;\n    private static Method regDeleteValue = null;\n\n    static {\n        try {\n            regOpenKey = userClass.getDeclaredMethod("WindowsRegOpenKey", new Class[] {int.class, byte[].class, int.class});\n            regOpenKey.setAccessible(true);\n            regCloseKey = userClass.getDeclaredMethod("WindowsRegCloseKey", new Class[] {int.class});\n            regCloseKey.setAccessible(true);\n            regQueryValueEx = userClass.getDeclaredMethod("WindowsRegQueryValueEx", new Class[] {int.class, byte[].class});\n            regQueryValueEx.setAccessible(true);\n            regEnumValue = userClass.getDeclaredMethod("WindowsRegEnumValue", new Class[] {int.class, int.class, int.class});\n            regEnumValue.setAccessible(true);\n            regQueryInfoKey = userClass.getDeclaredMethod("WindowsRegQueryInfoKey1", new Class[] {int.class});\n            regQueryInfoKey.setAccessible(true);\n            regEnumKeyEx = userClass.getDeclaredMethod("WindowsRegEnumKeyEx", new Class[] {int.class, int.class, int.class});  \n            regEnumKeyEx.setAccessible(true);\n            regCreateKeyEx = userClass.getDeclaredMethod("WindowsRegCreateKeyEx", new Class[] {int.class, byte[].class});  \n            regCreateKeyEx.setAccessible(true);\n            regSetValueEx = userClass.getDeclaredMethod("WindowsRegSetValueEx", new Class[] {int.class, byte[].class, byte[].class});  \n            regSetValueEx.setAccessible(true);\n            regDeleteValue = userClass.getDeclaredMethod("WindowsRegDeleteValue", new Class[] {int.class, byte[].class});  \n            regDeleteValue.setAccessible(true);\n            regDeleteKey = userClass.getDeclaredMethod("WindowsRegDeleteKey", new Class[] {int.class, byte[].class});  \n            regDeleteKey.setAccessible(true);\n        }\n        catch (Exception e) {\n            e.printStackTrace();\n        }\n    }\n\n    /**\n     * Reads value for the key from given path\n     * @param hkey   HKEY_CURRENT_USER/HKEY_LOCAL_MACHINE\n     * @param path\n     * @param key\n     * @return the value\n     * @throws IllegalArgumentException\n     * @throws IllegalAccessException\n     * @throws InvocationTargetException\n     * @throws IOException \n     */\n    public static String valueForKey(int hkey, String path, String key) \n            throws IllegalArgumentException, IllegalAccessException, InvocationTargetException, IOException {\n        if (hkey == HKEY_LOCAL_MACHINE)\n            return valueForKey(systemRoot, hkey, path, key);\n        else if (hkey == HKEY_CURRENT_USER)\n            return valueForKey(userRoot, hkey, path, key);\n        else\n            return valueForKey(null, hkey, path, key);\n    }\n\n    /**\n     * Reads all key(s) and value(s) from given path\n     * @param hkey  HKEY_CURRENT_USER/HKEY_LOCAL_MACHINE\n     * @param path\n     * @return the map of key(s) and corresponding value(s)\n     * @throws IllegalArgumentException\n     * @throws IllegalAccessException\n     * @throws InvocationTargetException\n     * @throws IOException \n     */\n    public static Map&lt;String, String&gt; valuesForPath(int hkey, String path) \n            throws IllegalArgumentException, IllegalAccessException, InvocationTargetException, IOException {\n        if (hkey == HKEY_LOCAL_MACHINE)\n            return valuesForPath(systemRoot, hkey, path);\n        else if (hkey == HKEY_CURRENT_USER)\n            return valuesForPath(userRoot, hkey, path);\n        else\n            return valuesForPath(null, hkey, path);\n    }\n\n    /**\n     * Read all the subkey(s) from a given path\n     * @param hkey  HKEY_CURRENT_USER/HKEY_LOCAL_MACHINE\n     * @param path\n     * @return the subkey(s) list\n     * @throws IllegalArgumentException\n     * @throws IllegalAccessException\n     * @throws InvocationTargetException\n     */\n    public static List&lt;String&gt; subKeysForPath(int hkey, String path)\n            throws IllegalArgumentException, IllegalAccessException, InvocationTargetException {\n        if (hkey == HKEY_LOCAL_MACHINE)\n            return subKeysForPath(systemRoot, hkey, path);\n        else if (hkey == HKEY_CURRENT_USER)\n            return subKeysForPath(userRoot, hkey, path);\n        else\n            return subKeysForPath(null, hkey, path);\n    }\n\n    /**\n     * Create a key\n     * @param hkey  HKEY_CURRENT_USER/HKEY_LOCAL_MACHINE\n     * @param key\n     * @throws IllegalArgumentException\n     * @throws IllegalAccessException\n     * @throws InvocationTargetException\n     */\n    public static void createKey(int hkey, String key) \n            throws IllegalArgumentException, IllegalAccessException, InvocationTargetException {\n        int [] ret;\n        if (hkey == HKEY_LOCAL_MACHINE) {\n            ret = createKey(systemRoot, hkey, key);\n            regCloseKey.invoke(systemRoot, new Object[] { new Integer(ret[0]) });\n        } else if (hkey == HKEY_CURRENT_USER) {\n            ret = createKey(userRoot, hkey, key);\n            regCloseKey.invoke(userRoot, new Object[] { new Integer(ret[0]) });\n        } else\n            throw new IllegalArgumentException("hkey=" + hkey);\n        if (ret[1] != REG_SUCCESS)\n            throw new IllegalArgumentException("rc=" + ret[1] + "  key=" + key);\n    }\n\n    /**\n     * Write a value in a given key/value name\n     * @param hkey\n     * @param key\n     * @param valueName\n     * @param value\n     * @throws IllegalArgumentException\n     * @throws IllegalAccessException\n     * @throws InvocationTargetException\n     */\n    public static void writeStringValue(int hkey, String key, String valueName, String value) \n            throws IllegalArgumentException, IllegalAccessException, InvocationTargetException {\n        if (hkey == HKEY_LOCAL_MACHINE)\n            writeStringValue(systemRoot, hkey, key, valueName, value);\n        else if (hkey == HKEY_CURRENT_USER)\n            writeStringValue(userRoot, hkey, key, valueName, value);\n        else\n            throw new IllegalArgumentException("hkey=" + hkey);\n    }\n\n    /**\n     * Delete a given key\n     * @param hkey\n     * @param key\n     * @throws IllegalArgumentException\n     * @throws IllegalAccessException\n     * @throws InvocationTargetException\n     */\n    public static void deleteKey(int hkey, String key) \n            throws IllegalArgumentException, IllegalAccessException, InvocationTargetException {\n        int rc = -1;\n        if (hkey == HKEY_LOCAL_MACHINE)\n            rc = deleteKey(systemRoot, hkey, key);\n        else if (hkey == HKEY_CURRENT_USER)\n            rc = deleteKey(userRoot, hkey, key);\n        if (rc != REG_SUCCESS)\n            throw new IllegalArgumentException("rc=" + rc + "  key=" + key);\n    }\n\n    /**\n     * delete a value from a given key/value name\n     * @param hkey\n     * @param key\n     * @param value\n     * @throws IllegalArgumentException\n     * @throws IllegalAccessException\n     * @throws InvocationTargetException\n     */\n    public static void deleteValue(int hkey, String key, String value) \n            throws IllegalArgumentException, IllegalAccessException, InvocationTargetException {\n        int rc = -1;\n        if (hkey == HKEY_LOCAL_MACHINE)\n            rc = deleteValue(systemRoot, hkey, key, value);\n        else if (hkey == HKEY_CURRENT_USER)\n            rc = deleteValue(userRoot, hkey, key, value);\n        if (rc != REG_SUCCESS)\n            throw new IllegalArgumentException("rc=" + rc + "  key=" + key + "  value=" + value);\n    }\n\n    // =====================\n\n    private static int deleteValue(Preferences root, int hkey, String key, String value)\n            throws IllegalArgumentException, IllegalAccessException, InvocationTargetException {\n        int[] handles = (int[]) regOpenKey.invoke(root, new Object[] {new Integer(hkey), toCstr(key), new Integer(KEY_ALL_ACCESS)});\n        if (handles[1] != REG_SUCCESS)\n            return handles[1];                                  // can be REG_NOTFOUND, REG_ACCESSDENIED\n        int rc =((Integer) regDeleteValue.invoke(root, new Object[] {new Integer(handles[0]), toCstr(value)})).intValue();\n        regCloseKey.invoke(root, new Object[] { new Integer(handles[0])});\n        return rc;\n    }\n\n    private static int deleteKey(Preferences root, int hkey, String key) \n            throws IllegalArgumentException, IllegalAccessException, InvocationTargetException {\n        int rc =((Integer) regDeleteKey.invoke(root, new Object[] {new Integer(hkey), toCstr(key)})).intValue();\n        return rc;                                                  // can REG_NOTFOUND, REG_ACCESSDENIED, REG_SUCCESS\n    }\n\n    private static String valueForKey(Preferences root, int hkey, String path, String key)\n            throws IllegalArgumentException, IllegalAccessException, InvocationTargetException, IOException {\n        int[] handles = (int[]) regOpenKey.invoke(root, new Object[] {new Integer(hkey), toCstr(path), new Integer(KEY_READ)});\n        if (handles[1] != REG_SUCCESS)\n            throw new IllegalArgumentException("The system can not find the specified path: \'"+getParentKey(hkey)+"\\\\"+path+"\'");\n        byte[] valb = (byte[]) regQueryValueEx.invoke(root, new Object[] {new Integer(handles[0]), toCstr(key)});\n        regCloseKey.invoke(root, new Object[] {new Integer(handles[0])});\n        return (valb != null ? parseValue(valb) : queryValueForKey(hkey, path, key));\n    }\n\n    private static String queryValueForKey(int hkey, String path, String key) throws IOException {\n        return queryValuesForPath(hkey, path).get(key);\n    }\n\n    private static Map&lt;String,String&gt; valuesForPath(Preferences root, int hkey, String path)\n            throws IllegalArgumentException, IllegalAccessException, InvocationTargetException, IOException {\n        HashMap&lt;String, String&gt; results = new HashMap&lt;String,String&gt;();\n        int[] handles = (int[]) regOpenKey.invoke(root, new Object[] {new Integer(hkey), toCstr(path), new Integer(KEY_READ)});\n        if (handles[1] != REG_SUCCESS)\n            throw new IllegalArgumentException("The system can not find the specified path: \'"+getParentKey(hkey)+"\\\\"+path+"\'");\n        int[] info = (int[]) regQueryInfoKey.invoke(root, new Object[] {new Integer(handles[0])});\n        int count = info[2];                            // Fixed: info[0] was being used here\n        int maxlen = info[4];                           // while info[3] was being used here, causing wrong results\n        for(int index=0; index&lt;count; index++) {\n            byte[] valb = (byte[]) regEnumValue.invoke(root, new Object[] {new Integer(handles[0]), new Integer(index), new Integer(maxlen + 1)});\n            String vald = parseValue(valb);\n            if(valb == null || vald.isEmpty())\n                return queryValuesForPath(hkey, path);\n            results.put(vald, valueForKey(root, hkey, path, vald));\n        }\n        regCloseKey.invoke(root, new Object[] {new Integer(handles[0])});\n        return results;\n    }\n\n    /**\n     * Searches recursively into the path to find the value for key. This method gives \n     * only first occurrence value of the key. If required to get all values in the path \n     * recursively for this key, then {@link #valuesForKeyPath(int hkey, String path, String key)} \n     * should be used.\n     * @param hkey\n     * @param path\n     * @param key\n     * @param list\n     * @return the value of given key obtained recursively\n     * @throws IllegalArgumentException\n     * @throws IllegalAccessException\n     * @throws InvocationTargetException\n     * @throws IOException\n     */\n    public static String valueForKeyPath(int hkey, String path, String key)\n            throws IllegalArgumentException, IllegalAccessException, InvocationTargetException, IOException {\n        String val;\n        try {\n            val = valuesForKeyPath(hkey, path, key).get(0);\n        } catch(IndexOutOfBoundsException e) {\n            throw new IllegalArgumentException("The system can not find the key: \'"+key+"\' after "\n                    + "searching the specified path: \'"+getParentKey(hkey)+"\\\\"+path+"\'");\n        }\n        return val;\n    }\n\n    /**\n     * Searches recursively into given path for particular key and stores obtained value in list\n     * @param hkey\n     * @param path\n     * @param key\n     * @param list\n     * @return list containing values for given key obtained recursively\n     * @throws IllegalArgumentException\n     * @throws IllegalAccessException\n     * @throws InvocationTargetException\n     * @throws IOException\n     */\n    public static List&lt;String&gt; valuesForKeyPath(int hkey, String path, String key)\n            throws IllegalArgumentException, IllegalAccessException, InvocationTargetException, IOException {\n        List&lt;String&gt; list = new ArrayList&lt;String&gt;();\n        if (hkey == HKEY_LOCAL_MACHINE)\n            return valuesForKeyPath(systemRoot, hkey, path, key, list);\n        else if (hkey == HKEY_CURRENT_USER)\n            return valuesForKeyPath(userRoot, hkey, path, key, list);\n        else\n            return valuesForKeyPath(null, hkey, path, key, list);\n    }\n\n    private static List&lt;String&gt; valuesForKeyPath(Preferences root, int hkey, String path, String key, List&lt;String&gt; list)\n            throws IllegalArgumentException, IllegalAccessException, InvocationTargetException, IOException {\n        if(!isDirectory(root, hkey, path)) {\n            takeValueInListForKey(hkey, path, key, list);\n        } else {\n            List&lt;String&gt; subKeys = subKeysForPath(root, hkey, path);\n            for(String subkey: subKeys) {\n                String newPath = path+"\\\\"+subkey;\n                if(isDirectory(root, hkey, newPath))\n                    valuesForKeyPath(root, hkey, newPath, key, list);\n                takeValueInListForKey(hkey, newPath, key, list);\n            }\n        }\n        return list;\n    }\n\n    /**\n     * Takes value for key in list\n     * @param hkey\n     * @param path\n     * @param key\n     * @param list\n     * @throws IllegalArgumentException\n     * @throws IllegalAccessException\n     * @throws InvocationTargetException\n     * @throws IOException\n     */\n    private static void takeValueInListForKey(int hkey, String path, String key, List&lt;String&gt; list)\n            throws IllegalArgumentException, IllegalAccessException, InvocationTargetException, IOException {\n        String value = valueForKey(hkey, path, key);\n        if(value != null)\n            list.add(value);\n    }\n\n    /**\n     * Checks if the path has more subkeys or not\n     * @param root\n     * @param hkey\n     * @param path\n     * @return true if path has subkeys otherwise false\n     * @throws IllegalArgumentException\n     * @throws IllegalAccessException\n     * @throws InvocationTargetException\n     */\n    private static boolean isDirectory(Preferences root, int hkey, String path)\n            throws IllegalArgumentException, IllegalAccessException, InvocationTargetException {\n        return !subKeysForPath(root, hkey, path).isEmpty();\n    }\n\n    private static List&lt;String&gt; subKeysForPath(Preferences root, int hkey, String path)\n            throws IllegalArgumentException, IllegalAccessException, InvocationTargetException {\n        List&lt;String&gt; results = new ArrayList&lt;String&gt;();\n        int[] handles = (int[]) regOpenKey.invoke(root, new Object[] {new Integer(hkey), toCstr(path), new Integer(KEY_READ)});\n        if (handles[1] != REG_SUCCESS)\n            throw new IllegalArgumentException("The system can not find the specified path: \'"+getParentKey(hkey)+"\\\\"+path+"\'");\n        int[] info = (int[]) regQueryInfoKey.invoke(root, new Object[] {new Integer(handles[0])});\n        int count  = info[0]; // Fix: info[2] was being used here with wrong results. Suggested by davenpcj, confirmed by Petrucio\n        int maxlen = info[3]; // value length max\n        for(int index=0; index&lt;count; index++) {\n            byte[] valb = (byte[]) regEnumKeyEx.invoke(root, new Object[] {new Integer(handles[0]), new Integer(index), new Integer(maxlen + 1)});\n            results.add(parseValue(valb));\n        }\n        regCloseKey.invoke(root, new Object[] {new Integer(handles[0])});\n        return results;\n    }\n\n    private static int [] createKey(Preferences root, int hkey, String key)\n            throws IllegalArgumentException, IllegalAccessException, InvocationTargetException {\n        return (int[]) regCreateKeyEx.invoke(root, new Object[] {new Integer(hkey), toCstr(key)});\n    }\n\n    private static void writeStringValue(Preferences root, int hkey, String key, String valueName, String value) \n            throws IllegalArgumentException, IllegalAccessException, InvocationTargetException {\n        int[] handles = (int[]) regOpenKey.invoke(root, new Object[] {new Integer(hkey), toCstr(key), new Integer(KEY_ALL_ACCESS)});\n        regSetValueEx.invoke(root, new Object[] {new Integer(handles[0]), toCstr(valueName), toCstr(value)}); \n        regCloseKey.invoke(root, new Object[] {new Integer(handles[0])});\n    }\n\n    /**\n     * Makes cmd query for the given hkey and path then executes the query\n     * @param hkey\n     * @param path\n     * @return the map containing all results in form of key(s) and value(s) obtained by executing query\n     * @throws IOException\n     */\n    private static Map&lt;String, String&gt; queryValuesForPath(int hkey, String path) throws IOException {\n        String line;\n        StringBuilder builder = new StringBuilder();\n        Map&lt;String, String&gt; map = new HashMap&lt;String, String&gt;();\n        Process process = Runtime.getRuntime().exec("reg query \\""+getParentKey(hkey)+"\\\\" + path + "\\"");\n        BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));\n        while((line = reader.readLine()) != null) {\n            if(!line.contains("REG_"))\n                continue;\n            StringTokenizer tokenizer = new StringTokenizer(line, " \\t");\n            while(tokenizer.hasMoreTokens()) {\n                String token = tokenizer.nextToken();\n                if(token.startsWith("REG_"))\n                    builder.append("\\t ");\n                else\n                    builder.append(token).append(" ");\n            }\n            String[] arr = builder.toString().split("\\t");\n            map.put(arr[0].trim(), arr[1].trim());\n            builder.setLength(0);\n        }\n        return map;\n    }\n\n    /**\n     * Determines the string equivalent of hkey\n     * @param hkey\n     * @return string equivalent of hkey\n     */\n    private static String getParentKey(int hkey) {\n        if(hkey == HKEY_CLASSES_ROOT)\n            return CLASSES_ROOT;\n        else if(hkey == HKEY_CURRENT_USER)\n            return CURRENT_USER;\n        else if(hkey == HKEY_LOCAL_MACHINE)\n            return LOCAL_MACHINE;\n        return null;\n    }\n\n    /**\n     *Intern method which adds the trailing \\0 for the handle with java.dll\n     * @param str String\n     * @return byte[] \n     */\n    private static byte[] toCstr(String str) {\n        if(str == null)\n            str = "";\n        return (str += "\\0").getBytes();\n    }\n\n    /**\n     * Method removes the trailing \\0 which is returned from the java.dll (just if the last sign is a \\0)\n     * @param buf the byte[] buffer which every read method returns\n     * @return String a parsed string without the trailing \\0\n     */\n    private static String parseValue(byte buf[]) {\n        if(buf == null)\n            return null;\n        String ret = new String(buf);\n        if(ret.charAt(ret.length()-1) == \'\\0\')\n            return ret.substring(0, ret.length()-1);\n        return ret;\n    }\n}  \n</code></pre>\n\n<p><strong>Sample of using the methods is as follows:</strong>    </p>\n\n<p>Below method retrieves the value of the key from the given path:  </p>\n\n<pre><code>String hex = WinRegistry.valueForKey(WinRegistry.HKEY_LOCAL_MACHINE, "SOFTWARE\\\\Microsoft\\\\Windows\\\\CurrentVersion\\\\WindowsUpdate\\\\Auto Update", "AUOptions");\n</code></pre>\n\n<p>This method retrieves all data for the specified path(in form of keys and values) :  </p>\n\n<pre><code>Map&lt;String, String&gt; map = WinRegistry.valuesForPath(WinRegistry.HKEY_LOCAL_MACHINE, "SOFTWARE\\\\Microsoft\\\\Windows\\\\CurrentVersion\\\\WSMAN");\n</code></pre>\n\n<p>This method retrieves value recursively for the key from the given path:  </p>\n\n<pre><code>String val = WinRegistry.valueForKeyPath(WinRegistry.HKEY_LOCAL_MACHINE, "System", "TypeID");\n</code></pre>\n\n<p>and this one retrieves all values recursively for a key from the given path:  </p>\n\n<pre><code>List&lt;String&gt; list = WinRegistry.valuesForKeyPath(\n                   WinRegistry.HKEY_LOCAL_MACHINE,                  //HKEY                               "SOFTWARE\\\\Wow6432Node\\\\Microsoft\\\\Windows\\\\CurrentVersion\\\\Uninstall",   //path                 "DisplayName"         //Key\n            );\n</code></pre>\n\n<p>Here in above code I retrieved all installed software names in windows system.<br>\n<strong>Note: See the documentation of these methods</strong>  </p>\n\n<p>And this one retrieves all subkeys of the given path:  </p>\n\n<pre><code>List&lt;String&gt; list3 = WinRegistry.subKeysForPath(WinRegistry.HKEY_CURRENT_USER, "Software");\n</code></pre>\n\n<p><strong>Important Note: I have modified only reading purpose methods in this process, not the writing purpose methods like createKey, deleteKey etc. They still are same as I recieved them.</strong> </p>\n'}, {'answer_id': 73575038, 'author': 'Gon Juarez', 'author_id': 9296473, 'author_profile': 'https://Stackoverflow.com/users/9296473', 'pm_score': 0, 'selected': False, 'text': '<p>I make my own code using enum.</p>\n<pre><code>    public class Registry {\n\n    public static enum key {\n        HKEY_CURRENT_USER, HKEY_USERS, HKEY_LOCAL_MACHINE, HKEY_CURRENT_CONFIG;\n    };\n\n    public static enum dataType {\n        REG_BINARY, REG_DWORD, REG_EXPAND_SZ, REG_MULTI_SZ, REG_SZ, REG_RESOURCE_LIST, REG_RESOURCE_REQUIREMENTS_LIST, REG_FULL_RESOURCE_DESCRIPTOR, REG_NONE, REG_LINK, REG_QWORD;\n    }\n\n    public static enum userKey {\n        AppEvents, Console, Control_Panel, Enviroment, EUDC, Keyboard_Layout, Microsoft, Network, Printers, Software, System, Uninstall, Volatile_Enviroment;\n    }\n\n    public static void overWriteSoftwareInt(String key, String userKey, String path, String valueKey, String datatype, int value) {\n        try {\n            Process process = Runtime.getRuntime().exec(&quot;reg add &quot; + key + &quot;\\\\&quot; + userKey + &quot;\\\\&quot; + path + &quot; /t &quot; + datatype + &quot; /v \\&quot;&quot; + valueKey + &quot;\\&quot; /d &quot; + value);\n            process.waitFor();\n        } catch (IOException ex) {\n            //  Logger.getLogger(Registry.class.getName()).log(Level.SEVERE, null, ex);\n        } catch (InterruptedException ex) {\n            Logger.getLogger(Registry.class.getName()).log(Level.SEVERE, null, ex);\n        }\n    }\n    \n    public static void overWriteSoftwareString(String key, String userKey, String path, String valueKey, String datatype, int value) {\n        try {\n            Process process = Runtime.getRuntime().exec(&quot;reg add &quot; + key + &quot;\\\\&quot; + userKey + &quot;\\\\&quot; + path + &quot; /t &quot; + datatype + &quot; /v \\&quot;&quot; + valueKey + &quot;\\&quot; /d \\&quot;&quot; + value+&quot;\\&quot;&quot;);\n            process.waitFor();\n        } catch (IOException ex) {\n            //  Logger.getLogger(Registry.class.getName()).log(Level.SEVERE, null, ex);\n        } catch (InterruptedException ex) {\n            Logger.getLogger(Registry.class.getName()).log(Level.SEVERE, null, ex);\n        }\n    }\n\n    public static void deleteValue(String key, String userKey, String path, String valueKey) {\n        try {\n            Process process = Runtime.getRuntime().exec(&quot;reg delete &quot; + key + &quot;\\\\&quot; + userKey + &quot;\\\\&quot; + path + &quot; /v \\&quot;&quot; + valueKey + &quot;\\&quot; /f&quot;);\n            process.waitFor();\n        } catch (IOException ex) {\n            //  Logger.getLogger(Registry.class.getName()).log(Level.SEVERE, null, ex);\n        } catch (InterruptedException ex) {\n            Logger.getLogger(Registry.class.getName()).log(Level.SEVERE, null, ex);\n        }\n    }\n}\n</code></pre>\n<p>You can use this class following this example.</p>\n<pre><code>   Registry.deleteValue(Registry.key.HKEY_CURRENT_USER.name(), Registry.userKey.Software.name(), &quot;path&quot;, &quot;valueName&quot;);\n   Registry.overWriteSoftwareInt(Registry.key.HKEY_CURRENT_USER.name(), Registry.userKey.Software.name(), &quot;path&quot;, &quot;valueName&quot;, Registry.dataType.REG_DWORD.name(), 0);\n</code></pre>\n'}]
['https://Stackoverflow.com/questions/62289', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/-1/']