Computing Concepts with Java Essentials
Laboratory Notebook
Chapter 13 - Files and Exceptions


Your name:
Your email address:
Your student ID number:

Once this form has been customized for your institution, you can use this button to send your lab work. Be sure to read the instructions before starting your work.


Lab Objectives

To gain experience with


P1. Reading Text Files

You already know how to read data from a file and write data to a file, by using the system variables System.in and System.out together with command-line redirection (java myprog <input.txt >output.txt).

However, this approach is limited. You need to learn to use files directly in your program in the following situations:

In these situations, you need files. Java supports many file types. In this lab, you will learn about several of them: the FileInputStream,FileOutputStream and RandomAccessFile classes for reading and writing information in byte-sized chunks, and the FileReader and FileWriter classes that deal with files made up from characters.

To open a file, first define an object of type FileInputStream or FileReader and then pass the file name to the constructor.

FileInputStream myData = new FileInputStream("input.dat");
FileReader myText = new FileReader("input.txt");

You can read a single byte or character with the read method. If the method returns -1, you reached the end of the file.

Alternatively, you can turn the file object into one that has useful methods for reading higher-level information, such as an ObjectInputStream or a BufferedReader. .

To write output to a file, you make a FileOutputStream or FileWriter object. The write method writes a single byte or character.

File reading and writing can throw IOException objects. Generally, you simply want methods that access files declare that they can throw these exceptions.

public void readSomething(BufferedReader in) throws IOException

Catch the exceptions in a suitable spot, for example, in the main method.

Write a program which compares the contents of two text files. Have your program display the line number and text of the first pair of lines that differ.

First, prompt the user for the names of the two files. Then open each file. Remember to check for failure. Keep reading a line from each of them. Increment a line number counter. If both files come to an end at the same time, print a message indicating that both files are identical. If one of the inputs fails and the other does not, print a message indicating which file is shorter, then exit. If the two input lines are different, print the line number counter and both input lines, then exit. If the two input lines are identical, keep on reading.


P2. Reading Input Data in a Graphics Program

Consider a graphics program that prompts the user to define shapes by selecting menu options and clicking on a window. When the user is done, the user's work should be stored in a file so that the user can retrieve it later. Graphics can be stored in a variety of formats. Choosing the best format for a particular purpose involves factors such as speed, portability to different platforms and programs, and the storage space and transmission requirements. In this lab exercise, we will use a simple text file containing lines of the form:

Rectangle 100 325 30 45

That is, a square is specified by the x- and y-coordinates of it's top left corner, followed by it's width and height.

Your program should

Note: Every time the user starts, the added rectangles should be automatically displayed.

Now implement the rectangle drawing program.

In this exercise, you saved the data in text format. Change the program to save the Vector of rectangles in an ObjectOutputStream. When reading it back in, read it from an ObjectInputStream.


P3. Command Line Arguments

Extend your file comparison program in two ways. First, make it possible to specify the file names on the command line. Only ask the user for the file names when they are not specified. And support a command line flag to control the number of differences identified. That is:

differ -a file1.txt file2.txt       
   displays all differences
differ -n  file1.txt file2.txt
   displays the first n differences
   For example
differ -20   
   displays the first 20 differences and prompts the user for the file names

P4. Random Access

If a file stores records of fixed length, it is easy to locate any one of them. If the records are also in a sorted order, for example employee records sorted by name, it is also possible to implement a fast search strategy called binary search. Rather than having to step through every record, you can eliminate half of the records remaining at each stage of the search because they are either too big or too small.

Consider searching for the name "Mushroom" in the following listing of employee records. (Each record consists of a name and a salary figure.)

  Acorn, John         34000
  Barley, Lawrence    37500 
  Corn, Charlie       29000
  Flax, Winston       43700
  Grape, Priscilla    35800
  Kiwi, Rachel        28700
->Lime, Lucy          45400
  Melon, Walker       33000
  Nasturtium, Ken     57000
  Olive, Ollie        29500
  Pickle, Jim         32000
  Radish, Ruby        32500
  Squash, Slim        44700
  Turnip, Misha       27500

First, note that there are 14 records. Start in the middle, at record 7, "Lime". Compare it with the search term, "Mushroom". Since "Mushroom" > "Lime", there is no need to look for it in the lines containing "Acorn" through "Lime".

  Melon, Walker       33000
  Nasturtium, Ken     57000
  Olive, Ollie        29500
->Pickle, Jim         32000
  Radish, Ruby        32500
  Squash, Slim        44700
  Turnip, Misha       27500

Go to the middle again. This time the middle among records 8 through 14 is record 11,"Pickle". Similarly, since "Mushroom" < "Pickle", "Pickle" through "Turnip" can be eliminated from further consideration.

That leaves only records 8 through 10. The middle record is 9.

  Melon, Walker       33000
->Nasturtium, Ken     57000
  Olive, Ollie        29500

That record is larger than "Mushroom", so we are left with records 8 through 8, i.e. a single record.

->  Melon, Walker       33000

Since this is not a match, we see that the name Mushroom is not in the database!

Here is the pseudocode to locate the value e, using binary search.

from = 0; 
to = index of last record;  

while (from <= to)
{  int mid = (from + to) / 2;
   if (value at mid equals e) return mid;
   else if (value at mid comes before e)
      from = mid + 1;
   else
      to = mid - 1;
}
/* e not found */

For this exercise, you need to write two programs. The first program reads a file in the above text format and writes a RandomAccessFile in which each employee record is stored as a fixed-size string (padded with spaces, if necessary) of width 30 (i.e. 60 bytes), followed by the salary (as an 8-byte double). You may assume that the input file has already been sorted.

The second program reads the random access file, then prompts the user for an employee record to search. It employs the binary search record that was just outlined to either find and print the record, or to print that the name was not found.


Don't forget to send your answers when you're finished.