package randomAccess;
import java.io.EOFException;
import java.io.IOException;
import java.io.RandomAccessFile;
/**
* Class to print out a management hierarchy, given an employee ID.
*
* @author Bryan J. Higgs, 31 January, 2001.
*/
public class EmployeeTree
{
/**
* Main entry point.
*
* @param args command line arguments.
* args[0] is the name of the file to read.
* args[1] is the employee ID.
*/
public static void main(String[] args)
{
if (args.length < 2)
{
System.err.println(
"Usage: java randomAccess.EmployeeTree <file-to-read> <empID>");
return;
}
// Extract the filename
String fileName = args[0];
// Extract the employee ID
int empID = Integer.parseInt(args[1]);
RandomAccessFile file = null;
try
{
// Create random access file object for reading
file = new RandomAccessFile(fileName, "r");
// Print the management hierarchy
printTree(file, empID);
// end it with a fresh newline
System.out.println();
}
catch (IOException ex)
{
ex.printStackTrace();
}
finally
{
if (file != null)
{
try
{
file.close();
}
catch (IOException ex)
{
// Ignore
}
}
}
}
/**
* Prints out a management hierarchy, given an employee ID
*/
private static int printTree(RandomAccessFile file, int empID)
throws IOException
{
// Calculate position of employee record in file.
long position = (empID-1) * Employee.RECORD_SIZE;
// Seek to it.
file.seek(position);
// Read employee data
Employee emp = new Employee();
emp.read(file);
// Perform a sanity check
if (emp.getID() != empID)
{
throw new IllegalStateException(
"Employee IDs don't match:" + empID + ", " + emp.getID());
}
int level = 0; // Used for indentation
if (emp.getManagedBy() != Employee.NO_MANAGER)
{
// If employee has a manager, recurse
level = printTree(file, emp.getManagedBy());
// Indent to level
for (int i = 0; i < level; i++)
System.out.print(' ');
System.out.print("manages ");
}
// Print out employee name
System.out.println(emp.getName());
return ++level;
}
} |