How to Work with Properties in Java

See Java: Tips and Tricks for similar articles.

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.

  1. Open your text editor and type in the following Java statements:Java Source for PropertiesThe program prompts the user for the values of three properties (nickname, email address, and zip code). A Properties object is instantiated at line 10. The individual property values entered by the user are stored on the file that is created when instantiating a FileOutputStream object (line 11). The store method is used to write the properties to the file. The program then reads the properties by creating a FileInputStream object and loads the properties object from the file using the load method. 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.
  2. Save your file as WorkWithProperties.java.
  3. 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.Compile Properties
  4. Type in the command to run your program and hit Enter. Respond to the prompts with your nickname, email address, and zip code.Run PropertiesThe output displays the values of your properties that were read from the properties file.