import java.util.*;
import java.io.*;
/**
* AddressBook.java
*
* Created: Sun Mar 2 18:04:33 2003
*
* @author Stuart C. Shapiro
*/
public class AddressBook {
private SortedList book;
/**
* Creates a new AddressBook
, and loads it from the
* file emailList.txt
*
*/
public AddressBook (){
loadAddressBook();
}
/**
* Loads this AddressBook
from the file
* emailList.txt
.
* Abnormally terminates the program if the file is not found, or
* if there is an error reading from it.
*/
private void loadAddressBook() {
book = new SortedList();
BufferedReader reader = null;
try {
/* Read all the elements from the file, emailList.txt,
* which is expected to have two lines per address:
* a person's name; the person's email address.
*/
reader = new BufferedReader(new FileReader("emailList.txt"));
String input;
while ( (input = reader.readLine()) != null ) {
book = book.insert(new AddressCard(input, reader.readLine()));
} // end of while ()
reader.close();
} catch (FileNotFoundException e) {
System.out.println("emailList.txt not found.");
System.exit(1);
} catch (IOException e) {
System.out.println("Error reading emailList.");
System.exit(1);
}
}
/**
* Writes this AddressBook
into the file
* emailList.txt
.
*
*/
public void save () {
PrintWriter writer;
try {
writer = new PrintWriter(new FileOutputStream("emailList.txt"));
for (SortedList list = book; !list.isEmpty();
list = (SortedList)list.getRest()) {
AddressCard card = (AddressCard)list.getFirst();
writer.println(card.getName());
writer.println(card.getAddress());
} // end of for
writer.flush();
writer.close();
} catch (IOException e) {
System.out.println("ERROR writing emailList.txt");
} // end of try-catch
}
/**
* Returns a String representation of this AddressBook
.
*
* @return a String representation of this AddressBook
.
*/
public String toString() {
return book.toString();
}
/**
* Sorts the Email Address Book file, emailList.txt
.
*
* @param args a String[]
value
*/
public static void main (String[] args) {
(new AddressBook()).save();
} // end of main ()
}// AddressBook