Finding a specific registry key using java in windows

随声附和 提交于 2019-12-01 18:29:33
afzalex

I will use this class for your answer. Because it is written in pure java code.

  1. Have a WinRegistry class from here.
  2. Get a list of all keys in parent key.
  3. filter list to get the most appropriate key (Or exact key).
  4. Then you can check the value you want in this key.

Here is the code to help you :

List<String> ls = WinRegistry.readStringSubKeys(WinRegistry.HKEY_LOCAL_MACHINE,
    "SOFTWARE\\Wow6432Node\\Microsoft\\Windows\\CurrentVersion\\Uninstall\\");
String key = ls.stream().filter(st -> st.matches("Maxima.*")).findAny().get();

Now this key value will be Maxima-5.17.1_is1 (if present otherwise java.util.NoSuchElementException will be thrown). And you can use it to get any Value.

I would avoid forcing access to private methods, because:

  1. They may not be there in a future release of Java. Literally, the next minor update may not have those methods.
  2. Code is less portable if it can only work in the absence of a SecurityManager.

If you use reg.exe, your code is guaranteed to work in all versions of Java, at least for as long as Microsoft includes reg.exe with Windows:

ProcessBuilder builder = new ProcessBuilder("reg", "query",
    "HKEY_LOCAL_MACHINE\\SOFTWARE\\Wow6432Node\\Microsoft\\Windows\\CurrentVersion\\Uninstall");
Process reg = builder.start();
try (BufferedReader output = new BufferedReader(
    new InputStreamReader(reg.getInputStream()))) {

    Stream<String> keys = output.lines().filter(l -> !l.isEmpty());
    Stream<String> matches = keys.filter(l -> l.contains("\\Maxima"));
    Optional<String> key = matches.findFirst();
    // Use key ... 
}
reg.waitFor();
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!