- Can’t write Java preferences in Windows 10
- Groovy Shell warning “Could not open/create prefs root node …”
- 9 Answers 9
- Java warning: «WARNING: Could not open/create prefs root node Software\JavaSoft\Prefs. » #1
- Comments
- julienvollering commented Feb 10, 2017
- julienvollering commented Feb 10, 2017
- bbottema commented Nov 3, 2017
- avineela commented Dec 1, 2017
- ooluwadeyi commented Dec 11, 2017
- taigemao commented Jan 1, 2018
- amcilwee commented Jan 5, 2018
- Working with Windows registry using java.util.prefs.Preferences
- 2 Answers 2
- Чтение / запись в реестр Windows с использованием Java
- 24 ответа
Can’t write Java preferences in Windows 10
I’m trying to run a program that looks for Java preferences in Windows 10 using JDK 10.0.2 . If it finds them under the system node, it tries to copy them to the user’s own node and then the user can change them to their liking. I’m not having any luck in either reading or writing preferences. I’ve tried a few different JDKs at version 8 and then installed 10 on the theory that it might work better but it didn’t.
My program is an old game that I wrote several years ago. It worked fine the last time I ran it in 2012. (At that point, I was probably running JDK 6 and Windows XP .)
I found some code that uses preferences, which is a good bit simpler than my own, in another StackOverflow discussion, modified it a bit, and tried to run it to see if I could come up with an easily reproducible example:
Results
Debugger shows that systemRoot is «/» after this statement; no error so far.
Console produces this message:
Console produces this message and stacktrace:
Oct 01, 2018 5:09:38 PM java.util.prefs.WindowsPreferences openKey WARNING: Could not open windows registry node Software\JavaSoft\Prefs at root 0x80000002. Windows RegOpenKey(. ) returned error code 5. Exception in thread «main» java.lang.SecurityException: Could not open windows registry node Software\JavaSoft\Prefs at root 0x80000002: Access denied at java.prefs/java.util.prefs.WindowsPreferences.openKey(WindowsPreferences.java:553) at java.prefs/java.util.prefs.WindowsPreferences.openKey(WindowsPreferences.java:515) at java.prefs/java.util.prefs.WindowsPreferences.openKey(WindowsPreferences.java:501) at java.prefs/java.util.prefs.WindowsPreferences.putSpi(WindowsPreferences.java:652) at java.prefs/java.util.prefs.AbstractPreferences.put(AbstractPreferences.java:263) at Prefs01.main(Prefs01.java:13)
Based on the error messages I’m getting, I am under the impression that I have some kind of a Windows authorization issue: I’m not authorized to do what I’m trying to do in the Windows Registry. This makes no sense to me because there is only one UAC on this machine and it is an administrator; I don’t know of any way to run this program under a different UAC even if there were another UAC on the machine.
Can anyone shed some light on what is going wrong here and what I need to do to fix it?
Groovy Shell warning “Could not open/create prefs root node …”
I tried to open the Groovy Shell ( groovysh ) on Windows 8 and got the following output:
After printing the above message the shell started as expected.
9 Answers 9
Dennis answer is correct. However I would like to explain the solution in a bit more detailed way (for Windows User):
- Go into your Start Menu and type regedit into the search field.
- Navigate to path HKEY_LOCAL_MACHINE\Software\JavaSoft (Windows 10 seems to now have this here: HKEY_LOCAL_MACHINE\Software\WOW6432Node\JavaSoft )
- Right click on the JavaSoft folder and click on New -> Key
- Name the new Key Prefs and everything should work.
Alternatively, save and execute a *.reg file with the following content:
I was able to resolve the problem by manually creating the following registry key:
This is actually a JDK bug. It has been reported several times over the years, but only in 8139507 was it finally taken seriously by Oracle.
The problem was in the JDK source code for WindowsPreferences.java . In this class, both nodes userRoot and systemRoot were declared static as in:
This means that the first time the class is referenced both static variables would be initiated and by this the Registry Key for HKEY_LOCAL_MACHINE\Software\JavaSoft\Prefs (= system tree) will be attempted to be created if it doesn’t already exist.
So even if the user took every precaution in his own code and never touched or referenced the system tree, then the JVM would actually still try to instantiate systemRoot , thus causing the warning. It is an interesting subtle bug.
There’s a fix committed to the JDK source in June 2016 and it is part of Java9 onwards. There’s also a backport for Java8 which is in u202.
What you see is really a warning from the JDK’s internal logger. It is not an exception. I believe that the warning can be safely ignored . unless the user code is indeed wanting the system preferences, but that is very rarely the case.
Java warning: «WARNING: Could not open/create prefs root node Software\JavaSoft\Prefs. » #1
Comments
julienvollering commented Feb 10, 2017
When using one of the MIAmaxent functions that relies on the maxent.jar software (e.g. deriveVars, selectDVforEV, selectEV, plotResp), some users have reported the appearance of the following waring message:
«WARNING: Could not open/create prefs root node Software\JavaSoft\Prefs at root 0x80000002. Windows RegCreateKeyEx(. ) returned error code 5.»
The text was updated successfully, but these errors were encountered:
julienvollering commented Feb 10, 2017
This is a known java issue, and may be solved by following the procedure suggested by MKorsch on StackOverflow (http://stackoverflow.com/questions/16428098/groovy-shell-warning-could-not-open-create-prefs-root-node):
«1. Go into your Start Menu and type regedit into the search field.
2. Navigate to path HKEY_LOCAL_MACHINE\Software\JavaSoft (Windows 10 seems to now have this here: HKEY_LOCAL_MACHINE\Software\WOW6432Node\JavaSoft)
3. Right click on the JavaSoft folder and click on New -> Key
4. Name the new Key Prefs and everything should work.»
bbottema commented Nov 3, 2017
Above method solved it for me (executing FindBugs from Maven) under Windows 10 (with HKEY_LOCAL_MACHINE\Software\JavaSoft).
avineela commented Dec 1, 2017
Above method solved it for me (executing FindBugs from Maven) under Windows 10 (with HKEY_LOCAL_MACHINE\Software\JavaSoft).
ooluwadeyi commented Dec 11, 2017
This method worked for me too.
Thanks
taigemao commented Jan 1, 2018
@julienvollering Thank you, it works for me. But I actually added new keys to both locations 🙂
amcilwee commented Jan 5, 2018
Thank you. worked for me, but I’m not sure why I get the following error when I run the line:
Working with Windows registry using java.util.prefs.Preferences
I have some questions about the registry.
We have
it will return true.
After it:
We see that it has one child: «Windows». But
returns false. Why?
UPDATE
Ok. I have some mistakes. Let me try again: Why does
2 Answers 2
If you execute the code lines shown, in the order shown, when you get to the line
p does not anymore point to the user root, but to «/HKEY_CURRENT_USER/Software/Policies».
Btw you have a probable omission in your third code sample:
I stumbled on this one today. The answer you’ve accepted is completely wrong.
You seem to be under the impression that Java Preferences is a general tool to manipulate the Windows Registry. It is not. It just so happens that the default implementation of Preferences on the Windows platform happens to store its data in the Windows Registry.
The implementation on Windows stores stuff under the following Registry paths:
For systemRoot: HKEY_LOCAL_MACHINE\SOFTWARE\JavaSoft\Prefs
For userRoot : HKEY_CURRENT_USER\Software\JavaSoft\Prefs
(note: The registry paths changes a bit if you are using a 32bit JRE on a 64-bit OS but that has nothing to do with Java and everything to do with Windows. Sun’s code always use the above paths.)
The point to make is that you can maybe use Java Preferences interface to read or change values in the Windows Registry but only below the above registry paths. The reason why I say ‘maybe’ is that this is just how it happens to be at the moment. Sun/Oracle could at any point in time decide to not to use the Windows Registry or use the Windows Registry but without using sub-nodes, i.e. store everything in one big XML string or something. The point is that Java Preferences is designed to shield you from this.
A lot of Java software that use the Java Preferences provide their own implementation (which is pretty simple to do) to avoid Sun’s default implementation that uses the Windows Registry. Not everyone can write to the Windows Registry these days so that was a pretty bad design decision on Sun’s part. Fortunately very easy to change.
Чтение / запись в реестр Windows с использованием Java
Как можно читать/записывать в реестр Windows с помощью java?
24 ответа
Я знаю, что этот вопрос старый, но это первый результат поиска в google для «java read/write to registry». Недавно я нашел этот удивительный фрагмент кода, который:
- Может читать/писать в ЛЮБОЙ части реестра.
- НЕ ИСПОЛЬЗУЕТ JNI.
- НЕ ИСПОЛЬЗУЕТ ЛЮБЫЕ 3-Й ПАРТИИ/ВНЕШНИЕ ПРИЛОЖЕНИЯ ДЛЯ РАБОТЫ.
- НЕ ИСПОЛЬЗУЕТ WINDOWS API (напрямую)
Это чистый, Java-код.
Он использует отражение для работы, фактически получая доступ к частным методам в классе java.util.prefs.Preferences. Внутренности этого класса сложны, но сам класс очень прост в использовании.
Например, следующий код получает точное распределение окон из реестра:
Вот оригинальный класс. Просто скопируйте его, и он должен работать:
Мне не удалось найти и отдать должное оригинальному автору этого кода. Если вы найдете какие-либо подробности, добавьте комментарий, и я добавлю его здесь.
Вам действительно не нужен сторонний пакет. У Windows есть утилита reg для всех операций реестра. Чтобы получить формат команды, перейдите в прокси файл DOS и введите:
Вы можете вызвать reg через класс Runtime:
Редактирование клавиш и добавление новых можно выполнить с помощью команды выше. Чтобы прочитать реестр, вам нужно получить результирующий выход, и это немного сложно. Здесь код:
Java Native Access (JNA) — отличный проект для работы с родными библиотеками и поддерживает реестр Windows в платформе library (platform.jar) через Advapi32Util и Advapi32.
Обновление:. Вот фрагмент с некоторыми примерами того, как легко использовать JNA для работы с реестром Windows с помощью JNA 3.4.1,
Я сделал это, прежде чем использовать jRegistryKey. Это LGPL Java/JNI-библиотека, которая может делать то, что вам нужно. Вот пример того, как я использовал его для включения редактирования реестра через regedit, а также опции «Показать параметры папки» для себя в Windows через реестр.
Я увеличил чистый код Java, первоначально опубликованный Дэвидом, чтобы разрешить 32-разрядную секцию реестра с 64-разрядной JVM и наоборот. Я не думаю, что любые другие ответы касаются этого.
Да, используя API java.util.Preferences, поскольку его реализация использует реестр в качестве бэкэнд.
В конце концов, это зависит от того, что вы хотите сделать: сохранение предпочтений для вашего приложения — это то, что настройки действительно великолепны. Если вы хотите на самом деле изменить ключи реестра, не связанные с вашим приложением, вам понадобится приложение JNI, как описано Марк (бесстыдный кражи здесь):
Из быстрого google: Проверьте WinPack для JNIWrapper. Он имеет полную поддержку доступа к реестру Windows, включая чтение и запись.
В WinPack Demo реализовано средство просмотра реестра.
Существует также возможность вызова внешнего приложения, которое отвечает за чтение/запись реестра.
Из быстрого google:
Проверьте WinPack для JNIWrapper. Это имеет полный доступ к реестру Windows включая чтение и письмо.
У WinPack Demo есть средство просмотра реестра реализованный в качестве примера.
Существует также возможность вызова внешнего приложения, которое отвечает за чтение/запись реестра.
Здесь представлена модифицированная версия решения Олега. Я заметил, что в моей системе (Windows Server 2003) вывод «reg query» не разделяется вкладками (‘\ t’), а на 4 пробела.
Я также упростил решение, поскольку нить не требуется.
Благодаря оригинальному сообщению. Я обновил этот класс утилиты и воспользовался недостатками, которые были у него ранее, подумал, что это может помочь другим, поэтому размещайте здесь. Я также добавил некоторые дополнительные утилиты. Теперь он может читать любой файл в реестре Windows (включая REG_DWORD, REG_BINARY, REG_EXPAND_SZ и т.д.). Все методы работают как шарм. Просто скопируйте и вставьте его, и он должен работать. Вот отредактированный и измененный класс:
Пример использования методов:
Ниже метод извлекает значение ключа из заданного пути:
String hex = WinRegistry.valueForKey(WinRegistry.HKEY_LOCAL_MACHINE, «SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\WindowsUpdate\\Auto Update», «AUOptions»);
Этот метод извлекает все данные для указанного пути (в виде ключей и значений):
Map map = WinRegistry.valuesForPath(WinRegistry.HKEY_LOCAL_MACHINE, «SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\WSMAN»);
Этот метод извлекает значение рекурсивно для ключа из заданного пути:
String val = WinRegistry.valueForKeyPath(WinRegistry.HKEY_LOCAL_MACHINE, «System», «TypeID»);
и он извлекает все значения рекурсивно для ключа из заданного пути:
List list = WinRegistry.valuesForKeyPath( WinRegistry.HKEY_LOCAL_MACHINE, //HKEY «SOFTWARE\\Wow6432Node\\Microsoft\\Windows\\CurrentVersion\\Uninstall», //path «DisplayName» //Key );
Здесь, в приведенном выше коде, я получил все установленные имена программ в системе Windows.
Примечание. См. документацию по этим методам
И этот извлекает все подразделы данного пути:
List list3 = WinRegistry.subKeysForPath(WinRegistry.HKEY_CURRENT_USER, «Software»);
Важное примечание. В этом процессе я изменил только методы чтения цели, а не методы написания, такие как createKey, deleteKey и т.д. Они все равно такие же, как я их получил.