Java Reference
In-Depth Information
At any time, fp.getFilePointer() returns the current value of the pointer. We can position the pointer at any
byte in the file with seek . The following statement positions the pointer at byte n :
fp.seek(n); //n is an integer; can be as big as a long integer
For example, we can read the 10 th record into a Part variable with this:
fp.seek(108); //the 10th record starts at byte 108
Part part = new Part(fp.readInt(), fp.readDouble());
In general, we can read the n th record with this:
fp.seek((n - 1) * 12); //the nth record starts at byte (n - 1) * 12
Part part = new Part(fp.readInt(), fp.readDouble());
We note that 12 should normally be replaced by a symbolic constant such as PartRecordSize .
We now expand the parts example by using a more realistic part record. Suppose that each part now has four
fields: a six-character part number, a name, an amount in stock, and a price. The following is some sample data:
PKL070 Park-Lens 8 6.50
BLJ375 Ball-Joint 12 11.95
FLT015 Oil-Filter 23 7.95
DKP080 Disc-Pads 16 9.99
GSF555 Gas-Filter 9 4.50
END
The part name is written as one word so it can be read with the Scanner method next . Note that the part names
do not all have the same length. And remember that in order to use a random access file, all records must have the
same length—this way we can work out a record's position in the file. How, then, can we create a random access file of
part records if the part names have different lengths?
The trick is to store each name using the same fixed amount of storage. For example, we can store each name
using 20 characters. If a name is shorter than 20, we pad it with blanks to make up 20. If it is longer, we truncate it
to 20. However, it is better to use a length that will accommodate the longest name.
If we use 20 characters for storing a name, what will be the size of a part record? In Java, each character is stored
in 2 bytes. Hence, the part number (6 characters) will occupy 12 bytes, a name will occupy 40 bytes, the amount in
stock (integer) will take up 4 bytes, and the price (double) will require 8 bytes. This gives a total of 64 bytes for each
record.
We write the Part class as follows:
class Part {
String partNum, name;
int amtInStock;
double price;
public Part(String pn, String n, int a, double p) {
partNum = pn;
name = n;
amtInStock = a;
price = p;
}
Search WWH ::




Custom Search