Hello,

I need to print the contents of a Windows Registry folder (Display Names). I have posted what I have started with and would appreciate some help. It returns a null value at this point, even though there are items in this folder. Thank you.

import java.lang.reflect.Method;
import java.util.prefs.Preferences;

public class JavaRegistry {
    private static final int HKEY_CURRENT_USER = 0x80000001;
    private static final int KEY_QUERY_VALUE = 1;
    private static final int KEY_SET_VALUE = 2;
    private static final int KEY_READ = 0x20019;

    public static void main(String args[]) {
        final Preferences userRoot = Preferences.userRoot();
        final Preferences systemRoot = Preferences.systemRoot();
        final Class clz = userRoot.getClass();

        try {
            final Method openKey = clz.getDeclaredMethod("openKey",
                    byte[].class, int.class, int.class);
                  openKey.setAccessible(true);
            final Method closeKey = clz.getDeclaredMethod("closeKey",
                    int.class);
            closeKey.setAccessible(true);

            final Method winRegQueryValue = clz.getDeclaredMethod(
                    "WindowsRegQueryValueEx", int.class, byte[].class);
            winRegQueryValue.setAccessible(true);
            final Method winRegEnumValue = clz.getDeclaredMethod(
                    "WindowsRegEnumValue1", int.class, int.class, int.class);
            winRegEnumValue.setAccessible(true);
            final Method winRegQueryInfo = clz.getDeclaredMethod(
                    "WindowsRegQueryInfoKey1", int.class);
            winRegQueryInfo.setAccessible(true);

            byte[] valb = null;
            String vals = null;
            String key = null;
            Integer handle = -1;


            key = "HKEY_LOCAL_MACHINE\\SOFTWARE\\Adobe";
            handle = (Integer) openKey.invoke(systemRoot, toCstr(key), KEY_READ, KEY_READ);
            valb = (byte[]) winRegQueryValue.invoke(systemRoot, handle, toCstr("Display Name"));
            vals = (valb != null ? new String(valb).trim() : null);
            System.out.println("Adobe Products = " + vals);
            closeKey.invoke(Preferences.systemRoot(), handle);
            } catch (Exception e) {
            e.printStackTrace();
        }

    }
    private static byte[] toCstr(String str) {
        byte[] result = new byte[str.length() + 1];
        for (int i = 0; i < str.length(); i++) {
            result[i] = (byte) str.charAt(i);
        }
        result[str.length()] = 0;
        return result;
    }
}

OK, no other answers, so I'll have a go.
This is coding on wild side! You use refection to break into private methods that are not part of the public API. Even if you get this to work now, there's no guarantee that it won't break in the very next minor Java update. Seems dangerous to me.
Anyway, try it without the HKEY_LOCAL_MACHINE\\ in your key, I think that's already implied by systemRoot.
If you want a safer way to approach this, you can use ProcessBuilder to run the command line registry tool reg.exe, and stick to published public APIs. I can let you have some sample code if you want to try it.

commented: Good you mention about the private methods. +3

James,

I am really new to accessing the Registry, so some sample code would be very helpful. Thank you for your recommendations. I will try them out. Thanks again :)

Here's a small program that will query a value from the registry. It runs reg.exe with the appropriate command then parses the out pt to get the result. If you look at the help messages for reg.exe you'll see the other options, and you'll then need to add some parsing to get whatever other results you need. The only other options I've ever found are (1) a neat Java/dll package called LatteLib that works well, but seems to have vanished from the net a couple of years ago, and (2) very many variants on the code that hooks into the private methods of the Java Windows Preferences implementation (with the dangers that I mentionsed in my earlier post).
Anyway, here's some code that may be useful to you:

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

public class WindowsRegistry {

 // just read a simple value so far...
 // see reg.exe help (in a command window) for other options

 public static String queryValue(String key, String value) {
  // returns null if key/value not found (or other error)

  try {
   Process p = new ProcessBuilder("reg.exe", "QUERY", key, "/v", value)
     .redirectErrorStream(true).start();
   // (reg.exe requires parameters to be already tokenised)
   InputStream is = p.getInputStream();
   BufferedReader br = new BufferedReader(new InputStreamReader(is));

   String line;
   // scan output & parse interesting lines...
   while ((line = br.readLine()) != null) {
    System.out.println("Input: " + line);
    if (line.contains(value)) {
     // this line displays the value we are looking for
     int i = line.indexOf("REG_SZ");
     if (i >= 0) {
      String result = line.substring(i + 7).trim();
      is.close();
      return result;
     }
    }
    if (line.contains("Error")) {
     System.err.println("reg.exe error searching for: " + key
       + " " + value);
     System.err.println(line);
     is.close();
     return null;
    }
   }
   System.err.println("ERROR: unable to parse output from reg.exe");
   System.err.println("Searching for: " + key + " " + value);
   is.close();
  } catch (Exception e) {
   e.printStackTrace();
  }
  return null;
 }

 public static void main(String args[]) throws IOException {
  // a little demo...
  String res;
  res = WindowsRegistry.queryValue("HKCU\\Control Panel\\Desktop",
    "Wallpaper");
  System.out.println("Wallpaper path: \"" + res + "\"");

  res = WindowsRegistry.queryValue("HKCU\\Control Panel\\Desktop",
    "noSuchValue");
  System.out.println("Incorrect query returned: \"" + res + "\"");
 }
}
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.