Random+Access+Files

Reference: CH, pages 588-594
Every record in a Random Access file must be of fixed size. You can read and modify any byte stored at any location in the file. You can move the file pointer to any location that you want, a read command would read from this point; a write command overwrites what was already there.

In java you use a RandomAccessFile object. You supply a file name and the mode. “r” for read only, “rw” for read and write mode.

RandomAccessFile f = new RandomAccessFile(“itemData”, “rw”); f.seek(n) moves the file pointer to byte n counted from the beginning of file. n = f.getFilePointer; gives the current position of the file pointer. Files can be large. To find the length of file in bytes, use long data type long fileLength = f.length; You can move the file pointer by n*record size to the desired position ‘n’. writeInt, writeUTF, writeDouble methods are used.

Operations required on RandomAccessFile:
 * Add – appends a new record at the end of file
 * Insert -- Adds a new record to the file at any desired spot
 * Read -- Reads a record from the file
 * Update -- Updates a record
 * Delete -- Deletes a record

Add. This operation adds a new record into the file. To add, we: Insert. This operation inserts a new record into the file. To insert, we:
 * 1) Append record data to the end of file
 * 2) Add the key field and record number to the index

Read. This operation retrieves a requested record from the file. To retrieve a record, we:
 * 1) Get the spot where you want to insert,
 * 2) check if the spot is free
 * 3) write new data at this spot
 * 4) Add the key field and record number to the index

Update. This operation updates an existing record with new data, replacing the new data with the old. We:
 * 1) Search the index on key field to get the record number
 * 2) Seek file pointer to that position
 * 3) Read all the desired data

Delete. This operation removes a record from the file. To delete a record, we:
 * 1) Search the index on key field to get the record number
 * 2) Seek file pointer to the correct position
 * 3) Over write the new information on old data


 * 1) Search the index on key field to get the record number
 * 2) Mark the record for deletion by adding the record number to a list of spots available for overwriting
 * 3) Remove the keyfield from the index
 * 4) The record gets delete from the file at the time of insert, insert overwrites new data at the marked spot.
 * RAF code as done in class **