Notes
Slide Show
Outline
1
CS110 Lecture 24
Thursday, April 29, 2004
  • Announcements
    • exam answers, final project (WISE) posted
    • final exam Thursday, May 20, 8:00 AM McCormack, Floor 01, Room 0608             (easier than last Tuesday’s!)
  • Agenda
    • Teaching evaluations, department questionnaire
    • Questions
    • Final project
    • Files
    • Persistence
2
 
3
How the dispatch table works
  • In CLIShell loop:
    • get first token on the line: commandName
    • lookup commandObject with commandName key
    • send doIt() message
  • Each particular ShellCommand extends the abstract ShellCommand class, implementing doIt() in its own way
  • Polymorphism at work


4
How LoginInterpreter interpret works
  • get first token on the line
  • use  if - else if - else if … logic
    • if “exit” return false!  // leave loop in CLIlogin
    • if “register”       // create account for new user
    • if “help”            // give help
    • else                    // input is a username
5
Dispatch table vs if-else if-else if
  • To add new commands just add a table entry
  • Command semantics separate from syntax
  • Lots of design overhead, hard to understand
  • Good for large command sets that will grow    (Juno shell commands)
  • To add new commands must edit the main loop
  • Command semantics and syntax in same place
  • Quick and dirty, easy to understand and code
  • Good for small command sets that stay put      (Juno login loop)
6
How the dispatch table works (reprise)
  • In CLIShell loop:
    • get first token on the line: commandName
    • lookup commandObject with commandName key
    • send doIt() message
  • Each particular ShellCommand extends the abstract ShellCommand class, implementing doIt() in its own way
  • Polymorphism at work


7
How LoginInterpreter interpret works (reprise)
  • get first token on the line
  • use  if - else if - else if … logic
    • if “exit” return false!  // leave loop in CLIlogin
    • if “register”       // create account for new user
    • if “help”            // give help
    • else                    // input is a username
8
Dispatch table vs if-else if-else if
  • To add new commands just add a table entry
  • Command semantics separate from syntax
  • Lots of design overhead, hard to understand
  • Good for large command sets that will grow    (Juno shell commands)
  • To add new commands must edit the main loop
  • Command semantics and syntax in same place
  • Quick and dirty, easy to understand and code
  • Good for small command sets that stay put      (Juno login loop)
9
WISE
  • Final project due Thursday, May 13
  • Intermediate deliverables Tuesday, May 4,11 must show substantial progress – I will grade and return them promptly
  •  What classes will (might) you need?
    • WISE (with main)
    • Student, Course, Professor
    • StudentList, CourseList, ProfessorList
    • TimeOfDay
  • Do not count on exact input/output formats yet
10
I/O programming
  • I/O = input/output
  • I/O is hard
    • deals with real world beyond programmers control
    • Output easier than input (programmer knows more)
    • System.out.println() is straightforward
    • Terminal readLine() wraps hard to use System.in
  • java.io package provides lots of useful classes
  • I/O programming may throw many Exceptions
  • Even good tools are hard to use when topic is hard
  • Count on borrowing from code that works
11
Copy
  • Classic example dealing with file contents
  • Write Windows command line copy in Java:
  • > java Copy sourcefile targetfile
  • main in Copy.java (pseudocode):
    • open sourcefile for reading
    • open targetfile for writing
    • while (get stuff from sourcefile)                                   write stuff to targetfile
    • close both files
12
Copy1.java
  • FileReader  inStream = null; // 26, outside try
  • FileWriter outStream = null; // 27, outside try
  • try {
  •   inStream  = new FileReader(args[0]); // 32
  •   outStream = new FileWriter(args[1]); // 33
  •   while (…) {  // 36-38 copy loop
  •   }
  • catch    // various errors
  • 40: faulty command line input - give usage message
  • 44: source file not found (or not readable)
  •           target file not writeable
  • 47: something went wrong in actual read/write
13
Keyword finally
  •    try {
  •    }
  •    catch() {
  •    {
  •    finally {
  •       code here runs whether or not try works
  •    }
  • Copy1.java 53, 61: close files whether or not there was an error in processing (underlying OS may limit number of files you may have open)
  • try (lines 51, 63) since even closing a file may throw an Exception


14
FileReader/FileWriter i/o
  • int ch; // character read as an int (line 28)
  • while ((ch = inStream.read()) != -1) { // 36
  •    outStream.write(ch);
  • }
  • Java (and C) idiom: assignment statement x = y gets value of x , so
  •         (ch = inStream.read()) != EOF
    • sends instream a read() message
    • assigns returned int to variable ch
    • compares that int to EOF, declared final static, used by read() to signal end of file
    • result is true or false, so useful as while test
15
Copy2 using BufferedReader/Writer
  • BufferedReader inStream  = null;// lines 24, 25
  • BufferedReader outStream = null
  • String line;
  • try
  •   inStream  = new BufferedReader (                     new FileReader(argv[0]));
  •   outStream = ...
  •   while ((line = inStream.readLine()) != null)
  •       outStream.write( line );
  •       outStream.newLine(); // no ‘\n’ in line
  • BufferedReader/Writer handle whole lines (Strings)
  • readLine returns null at EOF
16
Streams/filters
  • data can be characters, Strings, bytes, objects,…
  • Streams connect to file, terminal, String, net, …
  • Always use same methods: read, write (polymorphism)
  • Examples:
    • copy: stream of characters, or of lines (Strings)
    • Profile: stream of lines, program counts kinds
    • TV: input stream from cable, output stream to screen

17
*Stream
classes
18
Profile
  • main in Profile.java (pseudocode):
    • declare and initialize counters
    • open Java source for reading
    • while (get a line from source file)                                   classify line, increment counters
    • close source file
    • print results
19
Persistence
  • Bank and Juno should remember state between invocations
    • read state from a file at startup
    • write state back at exit
  • Can imagine a text representation of the state
  • Better: Java knows how to save whole Objects
20
Bank (version 9)
  • Bank instance can be saved to a file
  • java Bank –f bankFileName
  • live demo …
  • if –f bankFileName && file exists
  •   read Bank from that file
  • else create new Bank()
  • visit bank
  • if –f bankFileName
  •   write Bank to that file


21
Bank (version 9)
  • public class Bank                   implements Serializable
  • java Bank –f bankFileName
  • if (bankFileName == null) {     theBank = new Bank( bankName );
  •   }
  •   else {
  •    theBank = readBank
  • ( bankName,  bankFileName );
  •   }
22
Read Bank instance from a file
  • private static Bank readBank(        String bankName, String bankFileName) {
  •   File file = new File( bankFileName );  if (!file.exists()) {              return new Bank( bankName );    }                                   ObjectInputStream inStream = null;    try {                              inStream = new ObjectInputStream(           new FileInputStream( file ) );    Bank bank = (Bank)inStream.readObject();  System.out.println(               "Bank state read from file " + bankFileName);                        return bank;
  •   }
23
Why read/write only Bank?
  • BankAccount and Month are also Serializable
  • Bank box-and-arrow picture shows that all objects of all types are pointed to (indirectly) by arrows starting in the Bank
  • private transient Terminal atm;
  • Terminal not saved when Bank is saved
24
Persistence
  • Juno version 10 is persistent
  • new Java keyword implements, as in implements Serializable
  • Serializable is an interface, not a class
  • Find out about interfaces in cs210          (and a little bit next week)
  • Java 1.5 does a cleaner job with persistence