Lesson 11 | Working with RandomAccessFile |
Objective | Explain how to use RandomAccessFile for random read/write access in Java |
Most input/output streams in Java read or write sequentially from start to end.
Sometimes, however, you need direct access to a specific location in a file—for example,
updating a record in a database-like file or reading a fixed-length record from the middle of a large file.
RandomAccessFile
provides this capability: it allows both reading and writing at arbitrary byte positions without reopening the file.
seek(long position)
."r"
(read-only) or "rw"
(read/write) mode.
public class RandomAccessFile
extends Object
implements DataInput, DataOutput, Closeable
public RandomAccessFile(String filename, String mode)
throws FileNotFoundException
public RandomAccessFile(File file, String mode)
throws IOException
The constructor immediately opens the file. If the file does not exist (and cannot be created in write mode), an exception is thrown.
int read()
— reads a single byte and returns its value (0–255) or -1
if end of file is reached.int read(byte[] b)
— fills the array with bytes and returns how many were actually read (may be less than b.length
).int read(byte[] b, int off, int len)
— reads up to len
bytes into a subsection of the array.void readFully(byte[] b)
— blocks until the array is completely filled; throws EOFException
if not enough bytes remain.void readFully(byte[] b, int off, int len)
— same as above but for a subsection of the array.readBoolean()
, readByte()
, readChar()
, readInt()
, readLong()
, readFloat()
, readDouble()
, readUTF()
.void write(int b)
— writes a single byte (lowest 8 bits of b
).void write(byte[] b)
— writes the entire array to the file.void write(byte[] b, int off, int len)
— writes a subsection of the array.writeBoolean()
, writeByte()
, writeChar()
, writeInt()
, writeLong()
, writeFloat()
, writeDouble()
, writeUTF(String s)
.long getFilePointer()
— returns the current position.void seek(long pos)
— repositions the pointer to a specific location.int skipBytes(int n)
— moves the pointer forward by n
bytes.FileDescriptor getFD()
— returns the underlying file descriptor.void close()
— closes the file, releasing system resources.
try (RandomAccessFile raf = new RandomAccessFile("records.dat", "rw")) {
long recordSize = 128; // fixed-length records
int recordNumber = 10;
// Move to start of the 10th record
raf.seek(recordNumber * recordSize);
// Read an integer field
int id = raf.readInt();
// Update a value
raf.writeUTF("Updated Name");
}
EOFException
is thrown if end-of-file is reached unexpectedly (e.g., when using readFully()
).
Other IOException
s occur if the file is closed or another I/O error happens.
RandomAccessFile
is useful for legacy binary file formats and record-based storage.