Search code examples
javaregistry

Removing registry keys is returning null - not sure why


     for (String path : regPath) {
                    if (WinRegistry.readStringSubKeys(WinRegistry.HKEY_CURRENT_USER, path) == null) {
                        System.out.println(path + " was null.");
                        continue;
                    }

                    List<String> ls = WinRegistry.readStringSubKeys(WinRegistry.HKEY_CURRENT_USER, path);
                    if (ls == null || ls.isEmpty()) {
                        return;
                    } else {
                        for (String sub : ls) {
                            sub = path + "\\" + sub;
                            System.out.println(sub);
                            if (WinRegistry.readStringSubKeys(WinRegistry.HKEY_CURRENT_USER, sub) == null) {
                                System.out.println(path + " was null.");
                                continue;
                            }
                            ls = WinRegistry.readStringSubKeys(WinRegistry.HKEY_CURRENT_USER, sub);
                            if (ls == null || ls.isEmpty()) {
                                return;
                            } else {
                                for (String subKey : ls) {
                                    subKey = sub + subKey;
                                    System.out.println(subKey);
                                }
                            }

                            System.out.println(sub);
                        }
                    }
                }

From one of the answers I came up with this! How can I make it so that it goes through all the keys of a given path?

I need to clear all information from last activity viewer, here it gives you the registry values that I need to remove.


Solution

  • The API for removing registry key is WinRegistry.deleteKey(int hkey, String key). But it throw java.lang.IllegalArgumentException: rc=5 key=??? if sub-key exists.

    For delete registry key recursively, you should implement a method like this:

    private static void deleteKeyAndSub(int hkey, String key) 
        throws IllegalArgumentException, IllegalAccessException, InvocationTargetException {
      List<String> ls = WinRegistry.readStringSubKeys(hkey, key);
      if(ls == null) {
        return;
      } else if(ls.isEmpty()) {
        WinRegistry.deleteKey(hkey, key);
      } else {
        for (String subkey : ls) {
          subkey = key+"\\"+subkey;
          //System.out.println("delete subkey - "+subkey);
          deleteKeyAndSub(hkey, subkey);
        }
        WinRegistry.deleteKey(hkey, key);
      }
    }