Java The Complete Reference, Seventh Edition

(Greg DeLong) #1

500 Part II: The Java Library


// Get a set-view of the keys.
Set states = capitals.keySet();

// Show all of the states and capitals.
for(Object name : states)
System.out.println("The capital of " +
name + " is " +
capitals.getProperty((String)name)
+ ".");

System.out.println();

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

Using store( ) and load( )


One of the most useful aspects ofPropertiesis that the information contained in aProperties
object can be easily stored to or loaded from disk with thestore( )andload( )methods. At
any time, you can write aPropertiesobject 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
thestore( )andload( )methods to store and retrieve the list. When the program executes, it
first tries to load the list from a file calledphonebook.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) {
Free download pdf