Granny's Programming Pearls
"inside of every large program is a small program struggling to get out"
JavaRanch.com/granny.jsp
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 8 in Action this week in the Java 8 forum!
JavaRanch » Java Forums » Java » Java in General
Bookmark "reading from a file using RandomAccessFile" Watch "reading from a file using RandomAccessFile" New topic
Author

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.
Richard
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
Author
Ranch Hand

Joined: Oct 01, 2003
Posts: 239
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 my Java Programming Cookbook, see HerbSchildt.com
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: reading from a file using RandomAccessFile
 
Similar Threads
How to detect the end of file
NX: (Contractors) File I/O class
java.nio.ByteBuffer?
file i/o question
Make a file of desired size using java ?