|
Java™ by example!
|
|
|
How do I get started with the Preferences API?
 The Preferences API, introduced in JDK1.4, allows you to save and retrieve user and system configuration data. What you typically would do before was to save this configuration data in an XML, INI or Properties file in a specified directory known to your application. When you use the preferences API, you don't care where this data is located. On a Windows machine, it'll be saved in the registry, even though it is subject to change in future releases. On linux, files will be used to save your preferences (/etc/.java/.systemPrefs for system preferences and USERHOME/.java/.userPrefs for user preferences). The Preferences API is very simple to use. Instantiate a Preferences object and use the method put to save a key, value pair. With get you can retrieve the values, even with another VM. The API uses the packagename to differentiate between preferences of different applications.
Here's an example where you can set some preferences. When it starts up, it fills up the fields according to their values in the backing store. com\esus\examples\preferences\Main.java:
Take a look at the Windows registry in the key \\HKEY_CURRENT_USER\SOFTWARE\JavaSoft\Prefs
. If you want to load these preferences from another application, specify the node. Main2.java:
outputs:
Notice also that by using userRoot you are working with preferences for that user. You can also work with system preferences (shared by all users) by specifying systemRoot. When you perform a get, you have 2 parameters: one for the key and one for the default value. Whenever the value is not available on the backing store, the default value will be returned, if specified. In the following example, PORT is not available on the backing store. Main3.java:
outputs:
Further Information
Author of answer: Joris Van den Bogaert
Comments to this answer are only viewable by members. Login or become a member!
|
|
|
|
|