Listing 4: ProcessRecords.java — Processes a random access file of employee records

import java.io.*;

class ProcessRecords
{
    public static void main(String[] args)
    {
        Employee e1 = new Employee("doe", "john", 1);
        Employee e2 = new Employee("dough", "jane", 2);

        RandomAccessFile f = null;
        try
        {
            // Create file; add two records:
            System.out.println("Populating file...");
            f = new RandomAccessFile("employees.dat", "rw");
            e1.write(f);
            e2.write(f);
            System.out.println("e1 = " + e1);
            System.out.println("e2 = " + e2);
            System.out.println();

            // Swap on re-reading:
            System.out.println("Reading file...");
            f.seek(Employee.size);
            e1.read(f);
            f.seek(0);
            e2.read(f);
            System.out.println("e1 = " + e1);
            System.out.println("e2 = " + e2);
        }
        catch (IOException e)
        {
            e.printStackTrace();
            return;
        }
        finally
        {
            if (f != null)
            {
                try
                {
                    f.close();
                }
                catch (IOException e)
                {
                    System.out.println(
                        "File close error: " + e
                                      );
                }
            }
        }
    }
}

/* Output:
Populating file...
e1 = {doe,john,1}
e2 = {dough,jane,2}

Reading file...
e1 = {dough,jane,2}
e2 = {doe,john,1}
*/
— End of Listing —