How to Work with Properties in Java

  • google plus

In Brief...

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.

Take our Introduction to Java Training course for free.

See the Course Outline and Register

Instructions

  1. Open your text editor and type in the following Java statements:
    Java Source for Properties
    The 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 Properties
    The output displays the values of your properties that were read from the properties file.

Author: Stephen Withrow

Stephen has over 30 years' experience in training, development, and consulting in a variety of technology areas including Java, C, C++, XML, JavaScript, AJAX, Tomcat, JBoss, Oracle, and DB2. His background includes design and implementation of business solutions on client/server, Web, and enterprise platforms. Stephen is a published writer in both technical and non-technical endeavors. Stephen received an undergraduate degree in Computer Science and Physics from Florida State University.

Discuss