4

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.

paulmelnikow
  • 16,895
  • 8
  • 63
  • 114
Alexis King
  • 43,109
  • 15
  • 131
  • 205
  • Possible duplicate of these questions: http://stackoverflow.com/questions/3784657/what-is-the-best-way-to-save-user-settings-in-java-application and http://stackoverflow.com/questions/4017137/how-do-i-save-preference-user-settings-in-java – DPlusV Jul 08 '12 at 05:25
  • I'm removing the Cocoa tags as this is a Java question. – paulmelnikow Dec 24 '12 at 06:35

2 Answers2

10

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");
Community
  • 1
  • 1
Barry Wark
  • 107,306
  • 24
  • 181
  • 206
-2

No. The closest thing is the property file system. You can have a property file (which is a key-value file). Generally, they need to be in the classpath of the java program you're running. You can also create property files (or xml files) anywhere you want to in the file system (like a known good place). NSUserDefaults uses something like a p-list stored somewhere in the your home directory's Library, using a standard naming an directory path. You would have to come up with your own standard in Java.

ipaul
  • 374
  • 1
  • 10