home
***
CD-ROM
|
disk
|
FTP
|
other
***
search
/
Chip 1998 November
/
Chip_1998-11_cd.bin
/
tema
/
Cafe
/
WDESAMPL.BIN
/
EmployeeFileAccessor.java
< prev
next >
Wrap
Text File
|
1997-08-23
|
3KB
|
143 lines
import java.io.*;
/**
* Provide file storage and retrieval of employee data objects.
*/
public class EmployeeFileAccessor
{
RandomAccessFile f;
/**
* Open the employee file; create it if it does not exist.
*/
public EmployeeFileAccessor(String fname)
throws IOException
{
f = new RandomAccessFile(fname, "rw");
}
/**
* Set the employee file to the beginning
*/
public void reset()
throws IOException
{
f.seek(0);
}
// The size, in bytes, of an employee record. Records are fixed-size, to
// allow for easy modification.
final static int recsize =
Name.MAX_LENGTH+1 + Section.MAX_LENGTH+1 + SSN.MAX_LENGTH+1 +1;
/**
* Write a new employee to the end of the file
*/
public void addEmployee(Employee e)
throws IOException
{
// Transfer field values to buffer
byte[] b = new byte[recsize];
int pos = 0;
int len = e.name.value().length();
e.name.value().getBytes(0, len, b, pos);
b[pos + len] = '\0';
pos += Name.MAX_LENGTH + 1;
String a = String.valueOf(e.section.value());
len = a.length();
a.getBytes(0, len, b, pos);
b[pos + len] = '\0';
pos += Section.MAX_LENGTH + 1;
len = e.ssn.value().length();
e.ssn.value().getBytes(0, len, b, pos);
b[pos + len] = '\0';
b[recsize-1] = '\n';
// Write buffer to file, as a fixed-size record
f.seek(f.length());
f.write(b);
}
/**
* Fetch the first or next employee from the file.
*/
public Employee getNextEmployee()
throws IOException
{
byte[] b = new byte[recsize];
int nchars;
System.out.println("About to read");
if ((nchars = f.read(b)) <= 0) return null;
System.out.println("Read " + nchars + " chars");
int pos = 0;
String n = new String(b, 0, pos, Name.MAX_LENGTH);
n = n.trim();
System.out.println("Fetched name='" + n + "'");
pos += Name.MAX_LENGTH + 1;
String a = new String(b, 0, pos, Section.MAX_LENGTH);
a = a.trim();
System.out.println("Fetched section=" + a);
pos += Section.MAX_LENGTH + 1;
String s = new String(b, 0, pos, SSN.MAX_LENGTH);
s = s.trim();
System.out.println("Fetched ssn=" + s);
Employee emp;
try
{
emp = new Employee(n, a, s);
}
catch (InvalidEmployeeException e)
{
System.out.println("Invalid employee read from file!");
return null;
}
return emp;
}
/**
* Read the employee file, and build a list of employee objects.
*/
EmployeeList buildEmployeeList()
{
EmployeeList elist = new EmployeeList();
Employee emp;
int noOfEmployees = 0;
try
{
reset();
}
catch (IOException ex)
{
return elist;
}
for (;;)
{
try
{
emp = getNextEmployee();
}
catch (IOException ex)
{
return elist;
}
if (emp == null) break;
noOfEmployees++;
elist.add(emp);
}
System.out.println("noOfEmployees=" + noOfEmployees);
return elist;
}
}