import java.io.*;
// Illustrates fixed-length-record I/O
public class Employee
{
// Attributes:
int empno;
String last;
String first;
// Class constants:
static final int LAST_MAX = 15;
static final int FIRST_MAX = 15;
static final int size = LAST_MAX*2 + FIRST_MAX*2 + 4;
static final byte fillByte = (byte) 0xFF;
public Employee(String last, String first, int empno)
{
this.last = last;
this.first = first;
this.empno = empno;
}
static void stringToBytes(String s, int max, byte[] dest,
int offset)
{
// Note that max must be even, so we
// don't get half a char.
byte[] bytes = s.getBytes();
for (int i = 0; i < max; ++i)
{
if (i < bytes.length)
dest[i + offset] = bytes[i];
else
dest[i + offset] = fillByte;
}
}
public byte[] stringsToBytes()
{
byte[] buffer = new byte[LAST_MAX*2 + FIRST_MAX*2];
stringToBytes(last, LAST_MAX*2, buffer, 0);
stringToBytes(first, FIRST_MAX*2, buffer, LAST_MAX*2);
return buffer;
}
public void write(RandomAccessFile f) throws IOException
{
f.write(stringsToBytes());
f.writeInt(empno);
}
public void read(RandomAccessFile f) throws IOException
{
byte[] buffer = new byte[LAST_MAX*2 + FIRST_MAX*2];
f.readFully(buffer);
last = new String(buffer, 0,
findDelim(buffer, 0, LAST_MAX*2));
first = new String(buffer, LAST_MAX*2,
findDelim(buffer, LAST_MAX*2,
FIRST_MAX*2));
empno = f.readInt();
}
public String toString()
{
return "{" + last + "," + first + "," + empno + "}";
}
int findDelim(byte[] buffer, int start, int max)
{ // Find first occurrence of 'fillbyte' in
// a trailing substring
// ... implementation omitted
}
}
End of Listing