Java Reference
In-Depth Information
reorganized, the record could be deleted physically (that is, not present in the new file). But how can we
change
the
information in an existing record? To do this, we must do the following:
1.
Locate the record in the file.
2.
Read it into memory.
3.
Change the desired fields.
4.
Write the updated record to the
same position
in the file from which it came.
This requires that our file be opened for both reading and writing. Assuming that the file already exists, it must be
opened with mode
rw
. We explain how to update a record whose part number is stored in
key
.
First we search the index for
key
. If it is not found, no record exists for this part. Suppose it is found in location
k
.
Then
index[k].recNum
gives its record number (
n
, say) in the parts file. We then proceed as follows (omitting error
checking in the interest of clarity):
fp.seek(PartRecordSize * (n - 1));
Part part = readPartFromFile(fp);
The record is now in memory in the variable
part
. Suppose we need to subtract
amtSold
from the amount in
stock. This could be done with this:
if (amtSold > part.amtInStock)
System.out.printf("Cannot sell more than you have: ignored\n");
else part.amtInStock -= amtSold;
Other fields (except the part number, since this is used to identify the record) could be updated similarly. When
all changes have been made, the updated record is in memory in part. It must now be written back to the file in the
same position from which it came. This could be done with this:
fp.seek(PartRecordSize * (n - 1));
writePartToFile(part, fp);
Note that we must call
seek
again since, after having read the record the first time, the file is positioned at the
beginning of the
next
record. We must re-position it at the beginning of the record just read before writing the updated
record. The net effect is that the updated record overwrites the old one.
Program P7.10 updates the
amtInStock
field of records in the parts file. The user is asked to enter a part number
and the amount sold. The program searches the index for the part number using a binary search. If found, the record
is retrieved from the file, updated in memory, and written back to the file. This is repeated until the user enters
E
.
Program P7.10
import java.io.*;
import java.util.*;
public class UpdateFile {
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 {
Scanner in = new Scanner(System.in);
Index[] index = retrieveIndex();
int numRecords = index[0].recNum;
Search WWH ::
Custom Search