Java Reference
In-Depth Information
}
}
public void save() {
try {
Files.createDirectories(file.getParent()); // Make sure we have
the directory
} catch (IOException e) {
System.err.println("I/O error creating directory. " +
e.getMessage());
e.printStackTrace();
System.exit(1);
}
try (ObjectOutputStream out = new ObjectOutputStream(
new
BufferedOutputStream(Files.newOutputStream(file)))){
System.out.println("Saving phone book");
out.writeObject(phonebook);
System.out.println("Done");
} catch(IOException e) {
System.err.println("I/O error saving phone book. " +
e.getMessage());
e.printStackTrace();
System.exit(1);
}
}
// Other members of the class as before...
private Path file = Paths.get(System.getProperty("user.home")).
resolve("Beginning Java
Stuff").resolve("Phonebook.bin");}
Directory "TryPhoneBook 2"
The new private data member file defines the path for the file where the map holding the phone book
entries is to be stored. The file object is used in the constructor that now reads the HashMap<> object
from the file if it exists. If it doesn't exist, the constructor does nothing, and the PhoneBook object uses
the default empty HashMap object. The cast of the reference returned by the readObject() method to
type HashMap<Person, BookEntry> causes the compiler to issue a warning message to the effect that
you have an unchecked cast. There is no way around this because the compiler cannot know what the
type of the object that is read from the file is. Everything is fine as long as you know what you are doing!
The save() method provides for storing the map away, so you need to call this method before ending the
program.
To make the program a little more interesting you could add a method to the PhoneBook class that lists all
the entries in a phone book. Ideally, the entries should be displayed in alphabetical order by name. One
way to do this would be to create a linked list containing the entries and use the static sort() method
that the Collections class defines to sort them. The sort() method expects an argument that is of type
List<> , where the type of elements in the list implements the Comparable<> interface. Thus, to be able
to sort the entries in the phone book, the BookEntry class must implement the Comparable<> interface.
This is quite easy to arrange:
Search WWH ::




Custom Search