Java How do you use the preference API? Where do t

2019-03-25 19:00发布

问题:

Say I have the following

Preferences prefs = Preferences.userRoot().node(this.getClass().getName());

String ID1 = "Test1";

System.out.println(prefs.getBoolean(ID1, true));

prefs.putBoolean(ID1, false);

//prefs.remove(ID1);
  1. Is this variable persistent the next time I execute my program?
  2. Where do these variables store?
  3. What is the proper way of utilizing this?
  4. Is the approach better than using properties files?

回答1:

  1. Yes, the value is persistent but only for the user. It won't be there for other users.
  2. This is OS specific. For Windows it uses the registry, for Linux I believe it uses hidden files in the user root, although I'm not 100% sure.
  3. You've got a pretty good example in your question.
  4. It is different, not better. Preferences are a way of transparently storing settings for an application. These settings may be updated in run time by a user (for example you could use prefs to store user specific settings). Preferences are not meant to be editable outside of the application. Properties files tend to store hard setting specific to an application. These settings are the same for each user and tend not to change often. Properties files are text files and tend to accompany an application on deployment. You can edit them easily using a text editor. It is fairly rare for an application to update properties files.