Wednesday 22 March 2017

The Legacy Classes and Interfaces - Java Tutorials ( Page - 3 of 3 )

Properties

Properties is a subclass of Hashtable. It is used to maintain lists of values in which the key is a String and the value is also a String. The Properties class is used by many other Java classes. For example, it is the type of object returned by System.getProperties( ) when obtaining environmental values.

Properties defines the following instance variable:

      Properties defaults;

This variable holds a default property list associated with a Properties object. Properties defines these constructors:

      Properties( )
      Properties(Properties propDefault)

The first version creates a Properties object that has no default values. The second creates an object that uses propDefault for its default values. In both cases, the property list is empty.

In addition to the methods that Properties inherits from Hashtable, Properties defines the methods listed in Table 15-14. Properties also contains one deprecated method: save( ). This was replaced by store( ) because save( ) did not handle errors correctly.


The Legacy Methods Defined by Properties

String getProperty(String key):  Returns the value associated with key. A null object is returned if key
is neither in the list nor in the default property list.

String getProperty(String key, String defaultProperty):  Returns the value associated with key. defaultProperty is returned if key is neither in the list nor in the default property list.

void list(PrintStream streamOut):  Sends the property list to the output stream linked to streamOut.

void list(PrintWriter streamOut):  Sends the property list to the output stream linked to streamOut.

void load(InputStream streamIn) throws IOException:  Inputs a property list from the input stream linked to streamIn.

Enumeration propertyNames( ):  Returns an enumeration of the keys. This includes those keys found in the default property list, too.

Object setProperty(String key, String value):  Associates value with key. Returns the previous value associated with key, or returns null if no such association exists. (Added by Java 2, for consistency.)

void store(OutputStream streamOut, String description):  After writing the string specified by description, the property list is written to the output stream linked to streamOut. (Added by Java 2.)


One useful capability of the Properties class is that you can specify a default property that will be returned if no value is associated with a certain key. For example, a default value can be specified along with the key in the getProperty( ) method—such as getProperty(“name”, “default value”). If the “name” value is not found, then “default value” is returned. When you construct a Properties object, you can pass another instance of Properties to be used as the default properties for the new instance. In this case, if you call getProperty(“foo”) on a given Properties object, and “foo” does not exist, Java looks for “foo” in the default Properties object. This allows for arbitrary nesting of levels of default properties.

The following example demonstrates Properties. It creates a property list in which the keys are the names of states and the values are the names of their capitals. Notice that the attempt to find the capital for Florida includes a default value.

  // Demonstrate a Property list.
  import java.util.*;

  class PropDemo {
    public static void main(String args[]) {
      Properties capitals = new Properties();
      Set states;
      String str;

      capitals.put("Illinois", "Springfield");
      capitals.put("Missouri", "Jefferson City");
      capitals.put("Washington", "Olympia");
      capitals.put("California", "Sacramento");
      capitals.put("Indiana", "Indianapolis");

      // Show all states and capitals in hashtable.
      states = capitals.keySet(); // get set-view of keys
      Iterator itr = states.iterator();

      while(itr.hasNext()) {
        str = (String) itr.next();
        System.out.println("The capital of " +
                           str + " is " +
                           capitals.getProperty(str)
                           + ".");
      }

      System.out.println();

      // look for state not in list -- specify default
      str = capitals.getProperty("Florida", "Not Found");
      System.out.println("The capital of Florida is "
                         + str + ".");
    }
  }

The output from this program is shown here:

  The capital of Missouri is Jefferson City.
  The capital of Illinois is Springfield.
  The capital of Indiana is Indianapolis.
  The capital of California is Sacramento.
  The capital of Washington is Olympia.

  The capital of Florida is Not Found.

Since Florida is not in the list, the default value is used.

Although it is perfectly valid to use a default value when you call getProperty( ), as the preceding example shows, there is a better way of handling default values for most applications of property lists. For greater flexibility, specify a default property list when constructing a Properties object. The default list will be searched if the desired key is not found in the main list. For example, the following is a slightly reworked version of the preceding program, with a default list of states specified. Now, when Florida is sought, it will be found in the default list:

  // Use a default property list.
  import java.util.*;

  class PropDemoDef {
    public static void main(String args[]) {
      Properties defList = new Properties();
      defList.put("Florida", "Tallahassee");
      defList.put("Wisconsin", "Madison");

      Properties capitals = new Properties(defList);
      Set states;
      String str;

      capitals.put("Illinois", "Springfield");
      capitals.put("Missouri", "Jefferson City");
      capitals.put("Washington", "Olympia");
      capitals.put("California", "Sacramento");
      capitals.put("Indiana", "Indianapolis");

      // Show all states and capitals in hashtable.
      states = capitals.keySet(); // get set-view of keys
      Iterator itr = states.iterator();

      while(itr.hasNext()) {
        str = (String) itr.next();
        System.out.println("The capital of " +
                           str + " is " +
                           capitals.getProperty(str)
                           + ".");
      }

      System.out.println();

      // Florida will now be found in the default list.
      str = capitals.getProperty("Florida");
      System.out.println("The capital of Florida is "
                         + str + ".");
    }
  }


Using store( ) and load( )

One of the most useful aspects of Properties is that the information contained in a Properties object can be easily stored to or loaded from disk with the store( ) and load( ) methods. At any time, you can write a Properties object to a stream or read it back. This makes property lists especially convenient for implementing simple databases. For example, the following program uses a property list to create a simple computerized telephone book that stores names and phone numbers. To find a person’s number, you enter his or her name. The program uses the store( ) and load( ) methods to store and retrieve the list. When the program executes, it first tries to load the list from a file called phonebook.dat. If this file exists, the list is loaded. You can then add to the list. If you do, the new list is saved when you terminate the program. Notice how little code is required to implement a small, but functional, computerized phone book.

  /* A simple telephone number database that uses
     a property list. */
  import java.io.*;
  import java.util.*;

  class Phonebook {
    public static void main(String args[])
      throws IOException
    {
      Properties ht = new Properties();
      BufferedReader br =
        new BufferedReader(new InputStreamReader(System.in));
      String name, number;
      FileInputStream fin = null;
      boolean changed = false;

      // Try to open phonebook.dat file.
      try {
        fin = new FileInputStream("phonebook.dat");
      } catch(FileNotFoundException e) {
        // ignore missing file
      }

      /* If phonebook file already exists,
         load existing telephone numbers. */
      try {
        if(fin != null) {
          ht.load(fin);
          fin.close();
        }
      } catch(IOException e) {
        System.out.println("Error reading file.");
      }

      // Let user enter new names and numbers.
      do {
        System.out.println("Enter new name" +
                           " ('quit' to stop): ");
        name = br.readLine();
        if(name.equals("quit")) continue;

        System.out.println("Enter number: ");
        number = br.readLine();

        ht.put(name, number);
        changed = true;
      } while(!name.equals("quit"));

      // If phone book data has changed, save it.
      if(changed) {
        FileOutputStream fout=new FileOutputStream("phonebook.dat");
        
        ht.store(fout, "Telephone Book");
        fout.close();
      }

      // Look up numbers given a name.
      do {
        System.out.println("Enter name to find" +
                           " ('quit' to quit): ");
        name = br.readLine();
        if(name.equals("quit")) continue;

        number = (String) ht.get(name);
        System.out.println(number);
      } while(!name.equals("quit"));
    }
  }


Collections Summary

The collections framework gives you, the programmer, a powerful set of well-engineered solutions to some of programming’s most common tasks. Consider using a collection the next time that you need to store and retrieve information. Remember, collections need not be reserved for only the “large jobs,” such as corporate databases, mailing lists, or inventory systems. They are also effective when applied to smaller jobs. For example, a TreeMap would make an excellent collection to hold the directory structure of a set of files. A TreeSet could be quite useful for storing project-management information. Frankly, the types of problems that will benefit from a collections-based solution are limited only by your imagination.

No comments:

Post a Comment