
// DirEntry class
// ============

import java.io.*;

public class DirEntry

/*	methods include :
		getSurname
		getForename
		getNumber
		toString
		open
		close
		clear
		read
		write
*/
{
	int phoneNumber;
	String forename, surname;

	// selector methods ..

	public String getSurname()
	{
		return surname;
	}

	public String getForename()
	{
		return forename;
	}

	public int getNumber()
	{
		return phoneNumber;
	}

	// constructor methods ..

	public DirEntry (String fName, String sName, int number)
	{
		forename = fName;
		surname = sName;
		phoneNumber = number;
	}

	public DirEntry()
	{
	} 

	public String toString()
	{
		return surname + ", " + forename + " " + phoneNumber + " ";
	}

	// class attributes and methods ..

	static RandomAccessFile file;

	public static boolean open(String fileName)
	// tries to open the named file; returns "true" if successful,
	// "false" otherwise
	{
		boolean res = true;
		try	{
			file = new RandomAccessFile(fileName,"rw");
		}
		catch (IOException e) {
			res = false;
		}
		return res;
	} // end of method "open"

	public static void close()
	// closes the currently opened file
	{
		try	{
			file.close();
		}
		catch (IOException e)
		    {
		}
	}



	public void clear ()
	// clear a "dirEntry" to appropriate "empty" values
	{
		forename = surname = null;
		phoneNumber = 0;
	} // end of "clear" method


	// details of the number of bytes a "dirEntry" occupies
	// on the backing store

	private static final int RECORD_STRING_SIZE = 15;
	private static final int RECORD_SIZE = (RECORD_STRING_SIZE * 2) + 4;

	public void read(int recNum) throws IOException
	// read a record from the specified RandomAccessFile
	{
		file.seek((long) recNum * RECORD_SIZE);

		phoneNumber = file.readInt();
		byte b1[] = new byte [RECORD_STRING_SIZE];
		file.readFully(b1);
		forename = new String (b1);
		byte b2[] = new byte[RECORD_STRING_SIZE];
		file.readFully(b2);
		surname = new String (b2);
	} // end of method "read"

	private byte[] process(String str) 
	{
	int i;
	byte res[] = new byte[RECORD_STRING_SIZE];
	byte temp[] = str.getBytes();
	for (i = 0; i < str.length();i++)
		res[i] = temp[i];
	for (i = str.length(); i < RECORD_STRING_SIZE; i++)
		res[i] = '\0';
	return res;
	} // end of method "process"


	public void write(int recNum) 
		throws IOException
	{
		file.seek((long) recNum * RECORD_SIZE);
		file.writeInt(phoneNumber);
		if (forename == null) throw new 
			IOException("trying to output unset forename");
		byte b1[] = process(forename);
		file.write(b1);
		if (surname == null) throw new
			IOException("trying to output unset surname");
		byte b2[] = process(surname);
		file.write(b2);
	} // end of method "write"

} // end of class DirEntry

