Java Reference
In-Depth Information
records have keys 1, 2, 3,… and that they are stored sequentially. However, we still
need to calculate the record size. Obviously, we can decide upon the size of each
String fi eld ourselves. For numeric fi elds, though, the byte allocations are fi xed by
Java (in a platform-independent fashion) and are as shown below.
4 bytes
8 bytes
fl oat
4 bytes
8 bytes
Class RandomAccessFile provides the following methods for manipulating the
above types:
readInt, readLong, readFloat, readDouble
writeInt, writeLong, writeFloat, writeDouble
It also provides similarly-named methods for manipulating the other primitive
types. In addition, it provides a method called writeChars for writing a (variable-
length) string. Unfortunately, no methods for reading/writing a string of fi xed size
are provided, so we need to write our own code for this. In doing so, we shall need
to make use of methods readChar and writeChar for reading/writing the primitive
type char .
Suppose we wish to set up an accounts fi le with the following fi elds:
account number ( long );
surname ( String );
initials ( String );
balance ( fl oat ).
N.B. When calculating the number of bytes for a String fi eld, do not make the
mistake of allocating only one byte per character. Remember that Java is based on
the unicode character set, in which each character occupies two bytes.
Now let's suppose that we decide to allocate 15 (unicode) characters to surnames
and 3 (unicode) characters to initials. This means that each surname will be allo-
cated 30 (i.e., 15 × 2) bytes and each set of initials will be allocated 6 (i.e., 3 × 2)
bytes. Since we know that a long occupies precisely 8 bytes and a fl oat occupies
precisely 4 bytes, we now know that record size = (8 + 30 + 6 + 4) bytes = 48 bytes.
Consequently, we shall store records starting at byte positions 0, 48, 96, etc. The
formula for calculating the position of any record on the fi le is then:
(Record No. -1) × 48
For example, suppose our RandomAccessFile object for the above accounts fi le
is called ranAccts . Then the code to locate the record with account number 5 is:; //(5-1)x48 = 192
Since method length returns the number of bytes in a fi le, we can always work
out the number of records in a random access fi le by dividing the size of the fi le by
Search WWH ::

Custom Search