Change java.util.prefs.Preferences directory

157 Views Asked by At

I'm currently building a flatpak for a java app but have ran into a small problem with the way it's saving settings. If possible I'd like to solve it without editing the program itself.

It stores settings using java.util.prefs.Preferences like so

prefs.put(prefname, val);

and this is saved at the default location $HOME/.java/.userPrefs

because I'm bundling openjdk with the app I'd prefer that the preferences weren't saved in the same place that the system install java would store them. I've tried passing these 2 arguments to change the default directory but in both cases the app still writes to $HOME/.java/.userPrefs

java -Djava.util.prefs.userRoot=$HOME/.var/app/com.test.App/data -jar App.jar
java -Duser.home=$HOME/.var/app/com.test.App/data -jar App.jar

I've already tried messing with file permissions and it didn't make a difference

1

There are 1 best solutions below

0
On

I played around with Java Preferences inside a Flatpak app as well and I found out following:

Setting the target directory as a parameter to java worked, however only if the _JAVA_OPTIONS environment variable was not manually set on the user's host. Not sure how likely it is that users set this, but it seems risky that our desired setting will be ignored in that case. Nevertheless here how it worked for me when the variable was not set:

java -Djava.util.prefs.userRoot=$HOME/.var/app/<yourappid>/config -jar yourapp.jar

Potentially better approach - setting it as an environment variable:

export _JAVA_OPTIONS=-Djava.util.prefs.userRoot=$HOME/.var/app/<yourappid>/config
java -jar yourapp.jar

It turned out that this would work more reliably since the user can not override it. Our overriding of _JAVA_OPTIONS of course only happens inside our Flatpak environment. The user's env variable remains unchanged. The approach with the environment variable might also work for your JAR launching another JAR use case

Note: I was using OpenJDK 17 and Flatpak 1.15.6