Win a copy of Re-engineering Legacy Software this week in the Refactoring forum
or Docker in Action in the Cloud/Virtualization forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

reading from a file using RandomAccessFile

 
Richard Mendoza
Ranch Hand
Posts: 48
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Can somebody give me a sample code that reads a file using RandomAccessFile?
Thank you.
Richard
 
Stan James
(instanceof Sidekick)
Ranch Hand
Posts: 8791
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Rats, I posted something once but can't find it now. In short, the idea is to seek() a position in the file, read or overwrite some number of bytes. This works nicely with fixed length records. If you know every record is exactly 40 bytes long, you can calculate the position for record n, read 40 bytes, overwrite those bytes with changes.
You can build an external index that maps keys to record numbers and do primitive indexed IO. Unfortunately you can't insert any bytes, so new records always go on the end. You can't delete any bytes either, so if you "delete" a record you can wipe out the bytes and keep a list of "available" record slots for future writes.
Hey, I found a part of the class I made. I was doing Test First coding, adding one function at a time. This was about half done, I think:

[ October 02, 2003: Message edited by: Stan James ]
 
Herb Schildt
Author
Ranch Hand
Posts: 253
6
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Here is another example. It is a short program that writes to and reads from a file using RandomAccessFile. Hope it helps.

The output is
First value is 19.4
Second value is 10.1
Fourth value is 33.0
Here is every other value:
19.4 123.54 87.9
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic