Hi, I have a question regarding the "best" way to work with a RandomAccessFile. I have a program that works, but which is probably rather crude, and so I am wanting to find out if there is a more efficient and elegant way to achieve what I'm doing.
My program writes records (a
String and an int) to a RandomAccessFile using a hashing algorithm. Collisions are dealt with using an overflow area (from a certain record onwards). If there is a collision, the file searches sequentially for empty slots or the end of the file and writes in the first empty slot.
The program also lists all records, simply just stepping through all records and outputting the ones that aren't empty.
It can search for a record (the String is the search field), using the hashing algorithm. If there is a record in the desired position and the String matches the searchstring, it asks if this is the desired record (does the rest of the data, i.e. the int, match?). If so, that's that, but if not, it seeks to the overflow area and steps through sequentially until it finds a record which the user is happy with or until the end of the file.
Finally, it can delete records, using a similar strategy for finding the record to be deleted.
My question is, are the following ways of doing things okay or really clumsy? I got this working through trial and error.
* I compare hash key*Record_length with file_name.length() before trying to read a record to avoid null error.
* To check if a record is empty, I seek to the desired position, declare a byte array of the length of the String field, use method readFully(byte_array), create a new String object using the byte array as argument, trim the String, and then check if the length of the String equals 0. If the String length is 0, the record is empty, and the program seeks again (to the beginning of the record, after reading the String) and writes.
* To compare a record with a search string, I do the whole thing described above with the byte array, the string object and the trimming, but instead of checking the length, I compare the String object with the search string.
* To "delete records", I actually overwrite the current records with a String based on an empty byte array, and an int with value 0. Thus, I'm not really deleting but just setting the values to default. Thus, the file can never decrease in length when data is removed. Is there a way to make a RandomAccessFile "shrink" when data is removed?
Thanks for reading all the way through my post!
[ October 11, 2005: Message edited by: Flo Powers ]
[ October 11, 2005: Message edited by: Flo Powers ]