skip to content

What is java.io.RandomAccessFile, how do its file pointer and r/rw/rws/rwd modes work, and when would you pick it over a FileChannel or stream?

level: middleimportance: should knowfreq 30%

answer

  1. one cursor over a byte array
  2. seek moves it, even past the end
  3. four mode strings, two of them synchronous
  4. content only versus content plus metadata
  5. shared pointer versus positional channel reads

basics

~20 s

RandomAccessFile reads and writes anywhere in a file through one file pointer that seek() moves. Mode "r" is read-only, "rw" opens or creates, "rws" and "rwd" also write updates synchronously. It suits simple record files; FileChannel suits concurrent or bulk I/O.

solid answer

~40 s

`RandomAccessFile` treats a file as a large byte array with one cursor, the **file pointer**: each read or write starts there and advances it, `getFilePointer()` reports it and `seek(pos)` moves it, even past the end, where only a later write grows the file. It implements `DataInput`/`DataOutput`, so `readInt()` and `writeLong()` give typed fields, high byte first. The mode is `"r"` (read-only), `"rw"` (opens or creates, never truncates), or `"rws"`/`"rwd"`, which also make each update reach the storage device synchronously: content and metadata for `rws`, content only for `rwd`. Any other string throws `IllegalArgumentException`. I'd use it for a small single-threaded record file; `FileChannel` when threads read different offsets at once (`read(buf, position)` leaves the shared position alone) or for mapping, locks and transfers; a stream for plain sequential I/O. `getChannel()` bridges the two.

code

java · 33 lines
java
import java.io.IOException;
import java.io.RandomAccessFile;

public class BalanceFile {
    static final int RECORD_SIZE = Long.BYTES + Integer.BYTES; // id, then balance

    static void setBalance(String path, long index, int balance) throws IOException {
        try (RandomAccessFile file = new RandomAccessFile(path, "rwd")) {
            file.seek(index * RECORD_SIZE + Long.BYTES);
            file.writeInt(balance);
        }
    }

    static int balance(String path, long index) throws IOException {
        try (RandomAccessFile file = new RandomAccessFile(path, "r")) {
            file.seek(index * RECORD_SIZE + Long.BYTES);
            return file.readInt();
        }
    }

    public static void main(String[] args) throws IOException {
        String path = args.length > 0 ? args[0] : "balances.bin";
        try (RandomAccessFile file = new RandomAccessFile(path, "rw")) {
            file.setLength(0);
            for (long id = 0; id < 3; id++) {
                file.writeLong(id);
                file.writeInt(100);
            }
        }
        setBalance(path, 1, 250);
        System.out.println(balance(path, 1)); // 250
    }
}

go deeper

for a junior

Recall that RandomAccessFile has one file pointer that seek() moves, and that the only modes are r, rw, rws and rwd; anything else throws IllegalArgumentException.

for a middle

Explain the pointer's edge cases: seeking past the end, read() returning -1 against readInt() throwing EOFException, and how rws and rwd correspond to force(true) and force(false).

for a senior

Show why one shared RandomAccessFile breaks under concurrent seek-and-read, and reach for FileChannel's positional read and write, which leave the position alone and are documented as thread-safe.

for a principal

Weigh per-write synchronous modes against batched force() calls for durability and throughput, and decide when a hand-rolled record file should give way to a mapped file or a database.

## What `RandomAccessFile` is `java.io.RandomAccessFile` (in the JDK since 1.0) opens one file for reading, and optionally writing, and lets you jump to any byte offset instead of walking the file from the start. Its Javadoc describes the file as **a large array of bytes** with a cursor into it, the **file pointer**. It is not a stream: it does not extend `InputStream` or `OutputStream`. It implements `DataInput` and `DataOutput` instead, so the same object can `readInt()`, `writeLong()` or `readFully(byte[])`, with multi-byte values written high byte first. ## The file pointer Every read and write starts at the file pointer and moves it past the bytes transferred. - `getFilePointer()` returns the current offset and `seek(long pos)` sets it. A negative offset throws `IOException`. - `seek()` may go **past the end of the file**. That alone does not change `length()`; the file grows only when you write at that position. - Reading at or past the end: `read()` returns `-1`, while typed readers such as `readInt()` throw `EOFException` when the bytes run out. - A write beyond the end grows the file. The bytes between the old end and the new data are **unspecified** (that is how `FileChannel.position(long)` describes it), so do not count on zeros. - `setLength(n)` truncates or extends the file and clamps the pointer to at most `n`; `skipBytes(n)` stops at the end of the file, unlike `seek()`. ## The four modes The mode string is checked when the file is opened. Any other value, including `"w"`, throws `IllegalArgumentException`. | Mode | Access | Missing file | Synchronous updates | |---|---|---|---| | `"r"` | read only; a write method throws `IOException` | `FileNotFoundException` | not applicable | | `"rw"` | read and write | created | no | | `"rws"` | read and write | created | content **and** metadata | | `"rwd"` | read and write | created | content only | - `"rw"` opens an existing file **without truncating** it. `FileOutputStream`, by contrast, truncates an existing file unless you open it for appending. - `"rws"` and `"rwd"` work much like `FileChannel.force(true)` and `force(false)`, except that they apply to every I/O operation; the Javadoc notes this is often more efficient than forcing by hand. `"rwd"` can save I/O operations because metadata such as the last-modification time need not be written each time. - The guarantee holds when the file is on a **local storage device**. For a file elsewhere, such as a network mount, the Javadoc makes no such guarantee. ## `RandomAccessFile`, `FileChannel` or a stream? | Need | Best fit | |---|---| | Read or write a file from start to end | a buffered `FileInputStream`/`FileOutputStream`, or the `Files` helpers | | Patch fixed-size records in a small single-threaded tool | `RandomAccessFile` | | Several threads reading different offsets at once | `FileChannel.read(ByteBuffer, long)` | | Memory mapping, file locks, zero-copy transfer, scatter/gather | `FileChannel` | | Open options such as `CREATE_NEW`, `APPEND`, `SYNC`, `DSYNC` | `FileChannel.open(Path, ...)` | Why `FileChannel` wins once the workload gets busy: - `RandomAccessFile` has **one shared file pointer**. A `seek()` followed by `readInt()` is two calls, and another thread can move the pointer between them; nothing in the class makes that pair atomic. - `FileChannel.read(ByteBuffer dst, long position)` and `write(ByteBuffer, long)` take the offset as an argument and do not modify the channel's position, and the `FileChannel` Javadoc states that file channels are safe for use by multiple concurrent threads. - In the JDK, `RandomAccessFile` keeps no read-ahead buffer (its only private buffer is an 8-byte scratch array for primitive values), so each single-byte `read()` is a native call. Loops over `readByte()` are slow; read whole records with `readFully(byte[])`. - `StandardOpenOption.SYNC` and `DSYNC` give a `FileChannel` the same guarantees as `"rws"` and `"rwd"`. ## Using both: `getChannel()` `getChannel()` (since 1.4) returns the single `FileChannel` tied to the same open file. Its position always equals the file pointer, so a `seek()` moves the channel and `channel.position(n)` moves the pointer, and a length change through either is seen by both. Closing either object closes the other. A channel from an `"r"` file is open for reading only and throws `NonWritableChannelException` on a write. This lets you read a header with typed `DataInput` calls and switch to positional or mapped access for the body. ## Updating one record, step by step 1. Work out the field's byte offset: `index * RECORD_SIZE` plus the field's offset inside the record. 2. `seek()` to it. 3. Write the field with the matching `DataOutput` method, such as `writeInt()`. 4. If the change must survive a crash, open with `"rwd"`, or call `getChannel().force(false)` after a batch of writes. Steps 2 and 3 must not interleave with another thread's `seek()` on the same object, which is the shared-pointer limit above.

  • Two threads share one RandomAccessFile and each calls seek() and then readInt() for its own record. What can go wrong, and how do you fix it?
    The file pointer is shared, so thread B's `seek()` can land between thread A's `seek()` and `readInt()`, and A reads B's record. Either guard each seek-and-read pair with a lock, give each thread its own `RandomAccessFile`, or switch to `FileChannel.read(ByteBuffer, long)`, which takes the offset as an argument and leaves the channel's position untouched.
  • How do the rws and rwd modes relate to FileChannel.force(), and when would you prefer force() instead?
    They act like `force(true)` and `force(false)` applied to every I/O operation, with the guarantee only for a local storage device. That suits small, critical updates. When you write many records and only need them durable at a commit point, open with `"rw"` and call `getChannel().force(false)` once per batch, or open a `FileChannel` with `DSYNC` only where every write must be durable.
  • What exactly happens if you seek() past the end of a file and then read or write?
    The seek itself leaves `length()` unchanged. A `read()` there returns `-1` and `readInt()` throws `EOFException`. A write grows the file to cover the new bytes; the bytes between the old end and the new data are unspecified, so a format that relies on them must write them explicitly or use `setLength()` and fill the gap itself.

  • Opening an existing file in "rw" mode empties it first.
  • Seeking past the end of the file makes the file longer straight away.
  • Two threads can safely share one RandomAccessFile for seek-then-read.
  • A "w" mode exists for write-only random access.
  • The rws and rwd modes guarantee durability on any file system, including network mounts.
  • RandomAccessFile extends InputStream, so it plugs into any stream API.

java.io.RandomAccessFile
Java 1.0
RandomAccessFile.getChannel()
Java 1.4

context