CS 136 - Lecture 24

  1. Files for Animals
    1. A simple file example
  2. More examples using trees

Files for Animals

Suggest writing out in either prefix or postfix traversal. Indicate whether question or answer by writing 'Q' or 'A', otherwise might not be able to reconstruct tree.

Can load in exactly same way: read root, read and attach left subtree, read and attach right subtree.

File operations are pretty straightforward:

// create a new input file with name fileName.
  DataInputStream inFile = new DataInputStream(new FileInputStream(fileName));
// read character from inFile and store in letter
  char letter = inFile.readChar();
    
// read string from inFile and store in contents
  String contents = inFile.readUTF();
// close file
  inFile.close();                     

// create a new output file with name fileName.
  DataOutputStream outFile = new DataOutputStream(new FileOutputStream(fileName));
// write character from letter onto outFile
  outFile.writeChar(letter);
// write string from contents onto outFile
  outFile.writeUTF(contents);
// close file        
  outfile.close();
These classes are found in package java.io, so you must include an import statement for them.

File operations can throw exceptions because not find file, hit end of file when reading, etc.! In Java, one must test for exceptions and provide code to execute when exceptions are raised.

Java file operations may raise exceptions of type IOException. Must surround code that may throw this exception by:

try
    {//code using files} 
catch (IOException exc)
    {//code to execute if exception raised}
In the above, exc is a parameter of type IOException. You can send it a toString message to get info on what went wrong in the block that follows it.

You can either put all of the code into one single try-catch block or put each command that may raise the exception in such a block. You will get syntax errors if you do not surround these file messages with a try-catch block.

Your program should not just ignore these exceptions. At a minimum it should print out a message and return to a consistent state.


A simple file example

On Cider Press in the CS 136 folder, you will find a program that demonstrates file I/O. The code is reproduced here.

More examples using trees

Examples using trees include:
  1. Parse trees (discussed earlier)
  2. Search trees (illustrate the value of level-order searches)
  3. Decision trees