// 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 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.
Yo u c a n t h e n a d d t o t h e l i s t . I f y o u d o , t h e n e w l i s t i s s a v e d w h e n y o u t e r m i n a t e
t h e 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) {
Search WWH :
Custom Search
Previous Page
Java SE 6 Topic Index
Next Page
Java SE 6 Bookmarks
Home