Java Reference
In-Depth Information
When a part number is read, we look for it in the index. Since the index is kept in order by part number, we search
it using a binary search. If the part number is present, it means the part has been stored already, so this record is
ignored. If it is not present, this is a new part, so its record is stored in the parts file parts.bin , provided we have not
already stored MaxRecords records.
A count is kept (in numRecords ) of the number of records read. The part number and the record number are then
inserted in the proper place in the index array.
When all the records have been stored, the index is saved in another file, index.bin . Before saving it, the unused
portion of index (the entries after index[numRecords] ) is filled with dummy records. The value of MaxRecords is the
first value sent to the file. This is followed by index[0] to index[MaxRecords] . Remember that index[0].recNum
contains the value of numRecords .
Suppose that parts.txt contains the following:
PKL070 Park-Lens 8 6.50
BLJ375 Ball-Joint 12 11.95
PKL070 Park-Lens 8 6.50
FLT015 Oil-Filter 23 7.95
DKP080 Disc-Pads 16 9.99
GSF555 Gas-Filter 9 4.50
FLT015 Oil-Filter 23 7.95
END
When Program P7.8 is run, it prints the following:
Duplicate part: PKL070 ignored
Duplicate part: FLT015 ignored
The index is as follows:
BLJ375 2
DKP080 4
FLT015 3
GSF555 5
PKL070 1
Next, we write a program that tests our index by first reading it from the file. The user is then asked to enter part
numbers, one at a time. For each, it searches the index for the part number. If it finds it, the index entry will indicate
the record number in the parts file. Using the record number, the part record is retrieved. If the part number is not
found in the index, then there is no record for that part. The program is shown as Program P7.9.
Program P7.9
import java.io.*;
import java.util.*;
public class UseIndex {
static final int StringFixedLength = 20;
static final int PartNumSize = 6;
static final int PartRecordSize = 64;
static int MaxRecords;
public static void main(String[] args) throws IOException {
RandomAccessFile fp = new RandomAccessFile("parts.bin", "rw");
Search WWH ::




Custom Search