A property in Java can be used to store a value and associate that value with a key. A common application of properties is storing user preferences. For example, a nickname can be stored in a properties file and retrieved at a later time by using a key of "nickName". To learn how to work with properties in Java, follow these four steps.
- Open your text editor and type in the following Java statements:
The program prompts the user for the values of three properties (nickname, email address, and zip code). A
Propertiesobject is instantiated at line 10. The individual property values entered by the user are stored on the file that is created when instantiating a
FileOutputStreamobject (line 11). The
storemethod is used to write the properties to the file. The program then reads the properties by creating a
FileInputStreamobject and loads the properties object from the file using the
loadmethod. The program echoes the values to the console. Change the string literals containing the path name of the file (
c:/JavaStuff) to a path that exists on your computer.
- Save your file as
- Open a command prompt and navigate to the directory containing your Java program. Then type in the command to compile the source and hit Enter.
- Type in the command to run your program and hit Enter. Respond to the prompts with your nickname, email address, and zip code.
The output displays the values of your properties that were read from the properties file.