[Image]

RandomAccessFiles

Creates a RandomAccessFile with names and salaries (money).   The program allocates 50 bytes for each record -
   42 bytes for the name field
     8 bytes for the salary field

The commands .writeUTF and .readUTF use the following system:
First a two bytes tell the length of the following string, and the following bytes contain the string (1 char per byte) .

The double value occupies 8 bytes. So there are 42 bytes left for the name = 2 bytes for length, 40 bytes for data. If shorter strings are recorded, the extra bytes are empty (wasted).

Important Commands

RandomAccessFile file = new RandomAccessFile("salaries.dat","rw");
Opens a RandomAccessFile for reading and writing.  

file.seek(50*pos);
Move the file-pointer to the record in positioin pos.  Assumes that each record occupies 50 bytes.  The first record is number 0.

try ... catch (IOException e)
Handles possible IO errors, such as attempting to write in a read-only file.

file.writeUTF(name)
Write a UTF String into the file.  Remember this String occupies 2 extra bytes.

file.writeDouble(salary);
Write a double value into the file - occupies 8 bytes.

if (name.length() > 40) { name = name.substring(0,40);}
Truncates the String to 40 bytes, to ensure it fits properly into the name field.

Comments

Java does not have a "record" construct, like the struct command in C++.  So it is not possible to read and write entire records at once.  Each field must be read and written one at a time.  This requires more programming and care than in other languages.

It is possible to write any fundamental data type (long, int, boolean, etc.)  The programmer must be careful to allocate the correct number of bytes for each type.

Strings can be written with with writeChars and read with readLine, but this reqires a "\n" to be added to the written String.  Otherwise the readLine command will read too far, searching for the end-of-line character.

All RandomAccessFile programming requires careful attention to individual bytes and numbers of bytes.