Java RandomAccessFile

RandomAccessFile keeps a file pointer that you can move anywhere with seek, then read or write typed values at that position. That makes it the simple tool for binary record files and for changing a few bytes without rewriting a file. This page explains how the pointer and the record layouts work, shows the traps, and measures why its unbuffered reads need care.

Contents

How RandomAccessFile works

RandomAccessFile has been in Java since 1.0. It opens a file for reading, or for reading and writing, and keeps one number for it: the file pointer, the byte offset where the next read or write happens. Every read or write moves the pointer forward by the number of bytes it handled, and seek(offset) moves it anywhere. Unlike a stream, the same object can read, jump back, overwrite and read again.

The class implements both DataInput and DataOutput, the same interfaces as DataInputStream and DataOutputStream. So it has readInt, writeLong, readDouble and so on, all in big-endian byte order, which makes its files readable by any Java program on any machine. Two design facts matter in practice:

  • It has no buffer. Each read or write call goes to the operating system, so many small calls are slow; the speed section shows how slow.
  • It has one pointer per open file. Two threads that each seek and then read can interleave and read each other's positions. For concurrent access, use FileChannel positional reads, described on the NIO channels page.
RandomAccessFile methods by group
GroupMethods
Pointerseek, getFilePointer, skipBytes
Sizelength, setLength
Bytesread(), read(byte[]), readFully, write(byte[])
Typed valuesreadInt/writeInt, readLong/writeLong, readDouble/writeDouble and the other primitives
Text (avoid for files people read)readLine, writeUTF, writeChars
NIO bridgegetChannel (Java 1.4)

The modes are "r", "rw", "rws" and "rwd"; the last two make every write wait for the storage device. They are compared with the NIO open options, including what syncing costs, on the file open options page. Reading text from a position, such as the end of a log, is on reading a text file, and overwriting text in place, with the writeUTF trap, on writing a text file. This page is about binary data. All programs were compiled and run on JDK 21.

Fixed-size records

When every record has the same size, record n starts at byte n × recordSize, so you can jump straight to it. The program stores accounts with this layout:

Record layout, 32 bytes per record
FieldTypeOffset in recordBytes
idint04
nameUTF-8, padded with zero bytes420
balancelong248

It writes five records, reads record 3 directly, then changes only the balance of record 1. The balances 1,000 to 5,000 make the changed value, 9,999, easy to spot. Finally it stores a Danish name that is longer than the 20-byte field.

Java
import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.Arrays;

public class FixedRecords {

    // Record layout: id (int, 4 bytes) + name (20 bytes, zero-padded) + balance (long, 8 bytes)
    static final int NAME_BYTES = 20;
    static final int RECORD_SIZE = 4 + NAME_BYTES + 8;

    static void write(RandomAccessFile f, int index, int id, String name, long balance)
            throws IOException {
        f.seek((long) index * RECORD_SIZE);
        f.writeInt(id);
        f.write(Arrays.copyOf(fit(name), NAME_BYTES));
        f.writeLong(balance);
    }

    // Cuts a name to at most NAME_BYTES of UTF-8 without splitting a character
    static byte[] fit(String name) {
        byte[] utf8 = name.getBytes(StandardCharsets.UTF_8);
        if (utf8.length <= NAME_BYTES) {
            return utf8;
        }
        int end = NAME_BYTES;
        while ((utf8[end] & 0xC0) == 0x80) {        // continuation byte: step back
            end--;
        }
        return Arrays.copyOf(utf8, end);
    }

    static String read(RandomAccessFile f, int index) throws IOException {
        f.seek((long) index * RECORD_SIZE);
        int id = f.readInt();
        byte[] raw = new byte[NAME_BYTES];
        f.readFully(raw);
        int len = 0;
        while (len < NAME_BYTES && raw[len] != 0) {
            len++;
        }
        long balance = f.readLong();
        return String.format("#%d id=%d name=%-8s balance=%d", index, id,
                new String(raw, 0, len, StandardCharsets.UTF_8), balance);
    }

    public static void main(String[] args) throws IOException {
        Path path = Files.createTempFile("accounts", ".dat");
        String[] names = {"Ana", "Ben", "Cho", "Dev", "Eli"};
        try (RandomAccessFile f = new RandomAccessFile(path.toFile(), "rw")) {
            for (int i = 0; i < names.length; i++) {
                write(f, i, 100 + i, names[i], 1000L * (i + 1));
            }
            System.out.println("records: " + f.length() / RECORD_SIZE + ", file size: "
                    + f.length() + " bytes");

            // Jump straight to record 3: offset 3 * 32 = 96
            System.out.println("read directly: " + read(f, 3));

            // Change one field in place: balance of record 1 is at 1 * 32 + 4 + 20 = 56
            f.seek(RECORD_SIZE + 4 + NAME_BYTES);
            f.writeLong(9999);
            System.out.println("after in-place update, size still " + f.length() + " bytes");

            for (int i = 0; i < names.length; i++) {
                System.out.println("  " + read(f, i));
            }

            // A name longer than 20 bytes of UTF-8
            String longName = "Søren Kierkegård-Æbelø";
            byte[] naive = Arrays.copyOf(longName.getBytes(StandardCharsets.UTF_8), NAME_BYTES);
            System.out.println("long name: " + longName.length() + " chars, "
                    + longName.getBytes(StandardCharsets.UTF_8).length + " bytes in UTF-8");
            System.out.println("  cut at byte 20: " + new String(naive, StandardCharsets.UTF_8)
                    .replace("\uFFFD", "<U+FFFD>"));
            write(f, 5, 105, longName, 6000);
            System.out.println("  stored safely:  " + read(f, 5));
        }
        Files.delete(path);
    }
}

Output:

Output
records: 5, file size: 160 bytes
read directly: #3 id=103 name=Dev      balance=4000
after in-place update, size still 160 bytes
  #0 id=100 name=Ana      balance=1000
  #1 id=101 name=Ben      balance=9999
  #2 id=102 name=Cho      balance=3000
  #3 id=103 name=Dev      balance=4000
  #4 id=104 name=Eli      balance=5000
long name: 22 chars, 26 bytes in UTF-8
  cut at byte 20: Søren Kierkegård-<U+FFFD>
  stored safely:  #5 id=105 name=Søren Kierkegård- balance=6000
  • Five records of 32 bytes give a 160-byte file. Record 3 was read by seeking to byte 96, without reading records 0 to 2.
  • The update seeks to byte 56 (record 1 at 32, plus 4 for the id, plus 20 for the name) and overwrites 8 bytes. The file size did not change and no other record moved. This is the main reason to use fixed-size binary records: in a text format such as CSV, a value that gets longer forces a rewrite of everything after it.
  • The name has 22 characters but 26 bytes in UTF-8, because ø, ĂĄ and Æ take 2 bytes each. Cutting the bytes at 20 split the 2-byte Æ, and decoding ended with the replacement character U+FFFD, printed here as <U+FFFD>. The fit method steps back over UTF-8 continuation bytes (those starting with the bits 10) so the cut falls between characters.
  • The zero padding marks the end of a short name. A format that must store names containing zero bytes would need a length field instead.

The file pointer, gaps and the end of the file

The program writes four values of different sizes, prints the pointer after each, and then moves the pointer and the file length around to show the edge cases.

Java
import java.io.EOFException;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.file.Files;
import java.nio.file.Path;

public class PointerAndLength {

    public static void main(String[] args) throws IOException {
        Path path = Files.createTempFile("pointer", ".bin");
        try (RandomAccessFile f = new RandomAccessFile(path.toFile(), "rw")) {
            // Every read and write moves the pointer by the bytes it handled
            System.out.println("new file: pointer " + f.getFilePointer() + ", length "
                    + f.length());
            f.writeInt(7);
            System.out.println("after writeInt:      pointer " + f.getFilePointer());
            f.writeLong(42L);
            System.out.println("after writeLong:     pointer " + f.getFilePointer());
            f.writeDouble(2.5);
            System.out.println("after writeDouble:   pointer " + f.getFilePointer());
            f.writeShort(1);
            System.out.println("after writeShort:    pointer " + f.getFilePointer()
                    + ", length " + f.length());

            f.seek(0);
            int a = f.readInt();
            int skipped = f.skipBytes(8);                   // jump over the long
            double d = f.readDouble();
            System.out.println("read back: int " + a + ", skipped " + skipped
                    + " bytes, double " + d + ", pointer " + f.getFilePointer());
            System.out.println("skipBytes(100) near the end skipped only: " + f.skipBytes(100));

            // seek past the end, then write: the gap is filled with zeros
            f.seek(30);
            System.out.println("seek(30) on a " + f.length() + "-byte file: allowed, length still "
                    + f.length());
            f.write('!');
            f.seek(22);
            System.out.println("after writing at 30: length " + f.length() + ", byte 22 is "
                    + f.read());

            // setLength shrinks or grows; the pointer is clamped when shrinking
            f.setLength(6);
            System.out.println("setLength(6): length " + f.length() + ", pointer "
                    + f.getFilePointer());
            f.setLength(64);
            System.out.println("setLength(64): length " + f.length());

            // End of file: the typed reads throw, single-byte read returns -1
            f.seek(f.length());
            try {
                f.readInt();
            } catch (EOFException e) {
                System.out.println("readInt at end: EOFException");
            }
            System.out.println("read() at end: " + f.read());
            try {
                f.seek(-1);
            } catch (IOException e) {
                System.out.println("seek(-1): IOException: " + e.getMessage());
            }
        }
        Files.delete(path);
    }
}

Output:

Output
new file: pointer 0, length 0
after writeInt:      pointer 4
after writeLong:     pointer 12
after writeDouble:   pointer 20
after writeShort:    pointer 22, length 22
read back: int 7, skipped 8 bytes, double 2.5, pointer 20
skipBytes(100) near the end skipped only: 2
seek(30) on a 22-byte file: allowed, length still 22
after writing at 30: length 31, byte 22 is 0
setLength(6): length 6, pointer 6
setLength(64): length 64
readInt at end: EOFException
read() at end: -1
seek(-1): IOException: Negative seek offset
  • The pointer moved 4, 8, 8 and 2 bytes: the sizes of int, long, double and short. The file length followed it to 22.
  • skipBytes(8) jumped over the long. Near the end, skipBytes(100) skipped only the 2 bytes that were left and returned 2; it never moves past the end, so check its return value.
  • seek(30) on a 22-byte file was allowed and did not change the length. Writing there extended the file to 31 bytes, and the gap, such as byte 22, reads as 0. On file systems with sparse file support the gap takes no disk space.
  • setLength(6) truncated the file and moved the pointer back to 6, because it was beyond the new end. setLength(64) extended it; the Javadoc leaves the content of the extension undefined.
  • At the end, readInt threw EOFException while the single-byte read() returned -1. Loops over typed records should check getFilePointer() < length() rather than wait for an exception. seek(-1) threw IOException.

Variable-length records with an index

Fixed-size slots waste space when values vary a lot, and long values do not fit at all. The usual alternative is a length-prefixed record, an int length followed by the bytes, plus an index from key to offset. Updates append a new version and move the index entry, so existing records never have to move. Many storage engines, from log files to key-value stores, are built this way. The program stores three values of very different lengths, then updates one.

Java
import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.LinkedHashMap;
import java.util.Map;

// Variable-length records: [int length][UTF-8 bytes], found through an index of offsets
public class IndexedRecords {

    final RandomAccessFile file;
    final Map<String, Long> index = new LinkedHashMap<>();

    IndexedRecords(RandomAccessFile file) {
        this.file = file;
    }

    // Records are only ever appended; an update writes a new version and moves the index
    void put(String key, String value) throws IOException {
        long offset = file.length();
        byte[] bytes = (key + "=" + value).getBytes(StandardCharsets.UTF_8);
        file.seek(offset);
        file.writeInt(bytes.length);
        file.write(bytes);
        index.put(key, offset);
    }

    String get(String key) throws IOException {
        Long offset = index.get(key);
        if (offset == null) {
            return null;
        }
        file.seek(offset);
        byte[] bytes = new byte[file.readInt()];
        file.readFully(bytes);
        String record = new String(bytes, StandardCharsets.UTF_8);
        return record.substring(record.indexOf('=') + 1);
    }

    // Rebuilds the index by reading only the length fields and keys
    static Map<String, Long> scan(RandomAccessFile f) throws IOException {
        Map<String, Long> found = new LinkedHashMap<>();
        long pos = 0;
        while (pos < f.length()) {
            f.seek(pos);
            byte[] bytes = new byte[f.readInt()];
            f.readFully(bytes);
            String record = new String(bytes, StandardCharsets.UTF_8);
            found.put(record.substring(0, record.indexOf('=')), pos);  // later wins
            pos = f.getFilePointer();
        }
        return found;
    }

    public static void main(String[] args) throws IOException {
        Path path = Files.createTempFile("store", ".dat");
        try (RandomAccessFile f = new RandomAccessFile(path.toFile(), "rw")) {
            IndexedRecords store = new IndexedRecords(f);
            store.put("ana", "Lisbon");
            store.put("ben", "a much longer value that would not fit a fixed-size slot");
            store.put("cho", "Seoul");
            System.out.println("index: " + store.index);
            System.out.println("get(ben): " + store.get("ben"));

            store.put("ana", "Porto");                          // update by appending
            System.out.println("after update, index: " + store.index);
            System.out.println("get(ana): " + store.get("ana") + ", file size " + f.length());

            System.out.println("index rebuilt from the file: " + scan(f));
        }
        Files.delete(path);
    }
}

Output:

Output
index: {ana=0, ben=14, cho=78}
get(ben): a much longer value that would not fit a fixed-size slot
after update, index: {ana=91, ben=14, cho=78}
get(ana): Porto, file size 104
index rebuilt from the file: {ana=91, ben=14, cho=78}
  • "ana=Lisbon" is 10 bytes, so with its 4-byte length the record takes 14 bytes and "ben" starts at offset 14. The long value made "ben" 64 bytes, so "cho" starts at 78.
  • get("ben") did one seek, one readInt and one readFully, whatever the size of the file.
  • The update appended "ana=Porto" at offset 91 and moved the index entry. The old record is still in the file as dead space; real systems compact the file from time to time by copying the live records into a new one.
  • The index lives in memory, so scan rebuilds it from the file by hopping from length field to length field. Later records win, so it found the new "ana" at 91, the same index as before.

Why small reads are slow, and what to do instead

Because RandomAccessFile is unbuffered, the way a record is read matters a lot. The program reads 200,000 records of 32 bytes four ways and sums their last field, best of 3 runs each.

Java
import java.io.BufferedInputStream;
import java.io.DataInputStream;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.StandardOpenOption;

public class RecordReadSpeed {

    static final int RECORDS = 200000;
    static final int SIZE = 32;                             // int + 20 bytes + long

    interface Reader {
        long sum(Path p) throws IOException;
    }

    // Field by field: every readInt, readFully and readLong is a separate read
    static long fieldByField(Path p) throws IOException {
        long sum = 0;
        byte[] name = new byte[20];
        try (RandomAccessFile f = new RandomAccessFile(p.toFile(), "r")) {
            for (int i = 0; i < RECORDS; i++) {
                f.readInt();
                f.readFully(name);
                sum += f.readLong();
            }
        }
        return sum;
    }

    // One readFully per record, decoded from memory
    static long wholeRecord(Path p) throws IOException {
        long sum = 0;
        byte[] rec = new byte[SIZE];
        ByteBuffer view = ByteBuffer.wrap(rec);
        try (RandomAccessFile f = new RandomAccessFile(p.toFile(), "r")) {
            for (int i = 0; i < RECORDS; i++) {
                f.readFully(rec);
                sum += view.getLong(24);
            }
        }
        return sum;
    }

    static long bufferedStream(Path p) throws IOException {
        long sum = 0;
        byte[] name = new byte[20];
        try (DataInputStream in = new DataInputStream(
                new BufferedInputStream(Files.newInputStream(p), 64 * 1024))) {
            for (int i = 0; i < RECORDS; i++) {
                in.readInt();
                in.readFully(name);
                sum += in.readLong();
            }
        }
        return sum;
    }

    static long channelBlocks(Path p) throws IOException {
        long sum = 0;
        ByteBuffer buf = ByteBuffer.allocate(SIZE * 2048);  // 2,048 records per read
        try (FileChannel ch = FileChannel.open(p, StandardOpenOption.READ)) {
            while (ch.read(buf) != -1) {
                buf.flip();
                while (buf.remaining() >= SIZE) {
                    sum += buf.getLong(buf.position() + 24);
                    buf.position(buf.position() + SIZE);
                }
                buf.compact();
            }
        }
        return sum;
    }

    static void measure(String label, Path p, Reader r) throws IOException {
        long best = Long.MAX_VALUE;
        long sum = 0;
        for (int i = 0; i < 3; i++) {
            long start = System.nanoTime();
            sum = r.sum(p);
            best = Math.min(best, System.nanoTime() - start);
        }
        System.out.printf("%-40s %6.1f ms   sum %,d%n", label, best / 1e6, sum);
    }

    public static void main(String[] args) throws IOException {
        Path p = Files.createTempFile("records", ".dat");
        ByteBuffer all = ByteBuffer.allocate(RECORDS * SIZE);
        for (int i = 0; i < RECORDS; i++) {
            all.putInt(i).put(new byte[20]).putLong(i % 100);
        }
        Files.write(p, all.array());
        System.out.println(RECORDS + " records of " + SIZE + " bytes, best of 3");
        wholeRecord(p);                                     // warm-up
        measure("RandomAccessFile, field by field", p, RecordReadSpeed::fieldByField);
        measure("RandomAccessFile, one readFully/record", p, RecordReadSpeed::wholeRecord);
        measure("DataInputStream + BufferedInputStream", p, RecordReadSpeed::bufferedStream);
        measure("FileChannel, 64 KB blocks", p, RecordReadSpeed::channelBlocks);
        Files.delete(p);
    }
}

Output (rough comparison on a 2-CPU Linux VM, JDK 21; absolute times will differ on yours):

Output
200000 records of 32 bytes, best of 3
RandomAccessFile, field by field          151.5 ms   sum 9,900,000
RandomAccessFile, one readFully/record     50.3 ms   sum 9,900,000
DataInputStream + BufferedInputStream      13.8 ms   sum 9,900,000
FileChannel, 64 KB blocks                   2.6 ms   sum 9,900,000
  • Reading field by field made three calls per record: readInt, readFully and readLong, 600,000 in all. It was the slowest by far.
  • Reading each whole record with one readFully into a byte[32] and decoding it through a ByteBuffer made one call per record and was two to three times faster.
  • For sequential reading, a DataInputStream over a BufferedInputStream has the same readInt and readLong methods but serves them from memory. It was several times faster again.
  • A FileChannel reading 2,048 records per call was the fastest of all.

So use RandomAccessFile for what it is good at, jumping to a record and reading or writing it, and read whole records rather than single fields. To scan all records, use a buffered stream or a channel.

getChannel: one pointer, two APIs

getChannel() returns a FileChannel for the same open file. It is not a copy: the channel and the RandomAccessFile share the pointer and the bytes. The program moves the pointer through one and reads through the other.

Java
import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;

public class SharedPointer {

    public static void main(String[] args) throws IOException {
        Path path = Files.createTempFile("shared", ".txt");
        Files.writeString(path, "0123456789ABCDEFGHIJ");

        RandomAccessFile raf = new RandomAccessFile(path.toFile(), "rw");
        FileChannel ch = raf.getChannel();

        raf.seek(5);
        System.out.println("raf.seek(5) -> channel position " + ch.position());
        ch.position(12);
        System.out.println("ch.position(12) -> raf pointer " + raf.getFilePointer()
                + ", raf.read() gives '" + (char) raf.read() + "'");

        // A positional channel read leaves the shared pointer alone
        ByteBuffer buf = ByteBuffer.allocate(3);
        ch.read(buf, 0);
        System.out.println("ch.read(buf, 0) read \"" + new String(buf.array(),
                StandardCharsets.US_ASCII) + "\", raf pointer still " + raf.getFilePointer());

        // Bytes are shared too: no buffering on either side
        ch.write(ByteBuffer.wrap("xyz".getBytes(StandardCharsets.US_ASCII)), 0);
        raf.seek(0);
        byte[] first = new byte[3];
        raf.readFully(first);
        System.out.println("written by the channel, read by raf: "
                + new String(first, StandardCharsets.US_ASCII));

        raf.close();
        System.out.println("closing the RandomAccessFile closes its channel: " + !ch.isOpen());
        Files.delete(path);
    }
}

Output:

Output
raf.seek(5) -> channel position 5
ch.position(12) -> raf pointer 12, raf.read() gives 'C'
ch.read(buf, 0) read "012", raf pointer still 13
written by the channel, read by raf: xyz
closing the RandomAccessFile closes its channel: true
  • raf.seek(5) moved the channel's position to 5, and ch.position(12) moved the file pointer to 12, so raf.read() returned the byte at 12, 'C'.
  • ch.read(buf, 0) read "012" at offset 0 without touching the shared pointer, which stayed at 13. This positional read is the safe way to read one file from several threads.
  • Bytes written through the channel were immediately visible to the RandomAccessFile, because neither side buffers.
  • Closing the RandomAccessFile also closed the channel. Close either one, once.

Through the channel, an old RandomAccessFile program can also use memory mapping and file locks.

RandomAccessFile or something else?

Choosing an API for positional file access
NeedUse
Read or update one fixed-size recordRandomAccessFile with seek and one readFully or write per record
Values of very different sizesLength-prefixed records appended to the file, with an index of offsets
Read every record in orderDataInputStream over BufferedInputStream, or FileChannel with a large buffer
Several threads reading one fileFileChannel.read(buffer, position)
Random access to a large file as memoryFileChannel.map; see NIO channels and handling large files
The last lines of a text logSeek near the end and decode; see reading a text file
Replace text of the same byte lengthSeek and write encoded bytes; see writing a text file
Structured records with queriesAn embedded database instead of a hand-made format