File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Java in General and the fly likes reading from a file using RandomAccessFile Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login

Win a copy of Java Interview Guide this week in the Jobs Discussion forum!
JavaRanch » Java Forums » Java » Java in General
Bookmark "reading from a file using RandomAccessFile" Watch "reading from a file using RandomAccessFile" New topic

reading from a file using RandomAccessFile

Richard Mendoza
Ranch Hand

Joined: Feb 26, 2003
Posts: 48
Can somebody give me a sample code that reads a file using RandomAccessFile?
Thank you.
Stan James
(instanceof Sidekick)
Ranch Hand

Joined: Jan 29, 2003
Posts: 8791
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 ]

A good question is never answered. It is not a bolt to be tightened into place but a seed to be planted and to bear more seed toward the hope of greening the landscape of the idea. John Ciardi
Herb Schildt
Ranch Hand

Joined: Oct 01, 2003
Posts: 253
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

For my latest books on Java, including Introducing JavaFX 8 Programming, see
I agree. Here's the link:
subject: reading from a file using RandomAccessFile
It's not a secret anymore!