Java Reference
In-Depth Information
Random Access Files
Serial access fi les are simple to handle and are quite widely used in small-scale
applications or as a means of providing temporary storage in larger-scale applica-
tions. However, they do have two distinct disadvantages, as noted below.
(i) We can't go directly to a specifi c record. In order to access a particular record,
it is necessary to physically read past all the preceding records. For applications
containing thousands of records, this is simply not feasible.
(ii) It is not possible to add or modify records within an existing fi le. (The whole
fi le would have to be re-created!)
Random access fi les (probably more meaningfully called direct access fi les)
overcome both of these problems, but do have some disadvantages of their own…
(i) In common usage, all the (logical) records in a particular fi le must be of the
same length.
(ii) Again in common usage, a given string fi eld must be of the same length for all
records on the fi le.
(iii) Numeric data is not in human-readable form.
However, the speed and fl exibility of random access fi les often greatly outweigh
the above disadvantages. Indeed, for many real-life applications, there is no realistic
alternative to some form of direct access.
To create a random access fi le in Java, we create a RandomAccessFile object. The
constructor takes two arguments:
a string or File object identifying the fi le;
a string specifying the fi le's access mode.
The latter of these may be either “r” (for read-only access) or “rw” (for read-and-
write access). For example:
RandomAccessFile ranFile =
new RandomAccessFile("accounts.dat","rw");
Before reading or writing a record, it is necessary to position the fi le pointer . We
do this by calling method seek , which requires a single argument specifying the byte
position within the fi le. Note that the fi rst byte in a fi le is byte 0 . For example:;
//Move to byte 500 (the 501st byte).
In order to move to the correct position for a particular record, we need to know
two things:
the size of records on the fi le;
the algorithm for calculating the appropriate position.
The second of these two factors will usually involve some kind of hashing func-
tion that is applied to the key fi eld. We shall avoid this complexity and assume that
Search WWH ::

Custom Search