Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does Java have something similar to Cocoa's NSUserDefaults?

Mac OS X and iOS have a nice little class called NSUserDefaults. It's a singleton that lets you store strings, arrays, and primitives, and you can always implement some methods to add custom objects to it. It's super useful when you need to store a quick setting without dealing with file manipulations (for example, storing the last picked font name).

Does Java have something simple like this? I'd like to be able to store a user's last settings to reload a similar state when the program reloads, but I'm not sure what the best way to do this is in Java.

like image 413
Alexis King Avatar asked Feb 19 '23 22:02

Alexis King


1 Answers

Yes, you can use the java.util.prefs API. How do I save preference user settings in Java? and What is the best way to save user settings in java application? have some helpful info. To get you started:

[[NSUserDefaults standardUserDefaults] setString:@"some string" forKey:@"some_key"];

becomes

Preferences prefs = Preferences.userNodeForPackage(this);
prefs.put("some_key", "some string");

and

[[NSUserDefaults standardUserDefaults] stringForKey:@"some_key"];

becomes

Preferences prefs = Preferences.userNodeForPackage(this);
prefs.get("some_key");
like image 121
Barry Wark Avatar answered Feb 26 '23 10:02

Barry Wark