10. |
The preceding program is tedious to use because the user must type all appointment data into a series of dialog boxes. Improve the method so that the data can be stored in a file.
The simplest way to do this is to use input redirection. Put the data in a text file, say, appts.txt, and then run the program from a command shell such as
java AppointmentBookTest < appts.txt
The < shell operator links the standard input stream System.in to a file.
To read the input one line at a time, you need to turn System.in into a BufferedReader. Use the following class:
public class AppointmentBookReader { public AppointmentBookReader(InputReader reader) { in = new BufferedReader(reader); book = new AppointmentBook(); }
public AppointmentBook read() throws IOException, ParseException { boolean done = false; while (!done) { String input1 = in.readLine(); if (input1 == null) done = true; else { String input2 = in.readLine(); book.add(input1, input2); } } return book; } private BufferedReader in; private AppointmentBook book; }
To read from an appointment book, use the following code:
AppointmentBookReader bookReader = new AppointmentBookReader(new InputStreamReader( System.in)); AppointmentBook book = bookReader.read(); System.out.println(book);
Now change the AppointmentBookTest program so that it uses an AppointmentBookReader.
If there is any exception, describe the nature of the exception in English. Print the contents of the appointment book at the end of your program, whether or not there is any exception.
What is the complete code for your AppointmentBookTest class?
Answer:
|