EmployeeDataReader
Home ] Up ] Employee ] EmployeeDataLoader ] [ EmployeeDataReader ] EmployeeTree ]

 

 

Now, here's a class that reads the data back in from the file, reading employees sequentially:

package randomAccess;

import java.io.EOFException;
import java.io.IOException;
import java.io.RandomAccessFile;

/**
*   Class to read a set of employee data from a file.
*
*   @author Bryan J. Higgs, 31 January, 2001.
*/
public class EmployeeDataReader
{
    /**
    *   Main entry point.
    *
    *   @param args command line arguments.
    *               args[0] is the name of the file to read.
    */
    public static void main(String[] args)
    {
        if (args.length < 1)
        {
            System.err.println(
                "Usage: java randomAccess.EmployeeDataReader <file-to-read>");
            return;
        }
        // Extract the filename
        String fileName = args[0];

        RandomAccessFile file = null;
        try
        {
            // Create random access file object for reading
            file = new RandomAccessFile(fileName, "r");

            // Read the employees, in sequential order.
            while (true)
            {
                Employee emp = new Employee();
                emp.read(file);
                emp.print();
            }
        }
        catch (EOFException ex)
        {
            // Do nothing;  there are no more records to read
        }
        catch (IOException ex)
        {
            ex.printStackTrace();
        }
        finally
        {
            // Close file, under all circumstances.
            if (file != null)
            {
                try
                {
                    file.close();
                }
                catch (IOException ex)
                {
                    // Ignore
                }
            }
        }
    }
}

which produces the following output:

Employee ID: 1
       Name: Richie Rich
     Salary: $2000000.0
 Managed by: -1
Employee ID: 2
       Name: Guy Noire
     Salary: $200000.0
 Managed by: 1
Employee ID: 3
       Name: Prescott Hireling
     Salary: $100000.0
 Managed by: 1
Employee ID: 4
       Name: Dottie Magnusson
     Salary: $40000.0
 Managed by: 3
Employee ID: 5
       Name: Frank Getitdone
     Salary: $120000.0
 Managed by: 1
Employee ID: 6
       Name: Joe Duzit
     Salary: $30000.0
 Managed by: 5
 
The page was last updated February 19, 2008