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
RandomAccessFileseek(offset)
The class implements both DataInputDataOutputDataInputStreamDataOutputStreamreadIntwriteLongreadDouble
- 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
and thenseek can interleave and read each other's positions. For concurrent access, useread positional reads, described on theFileChannelNIO channels page .
| Group | Methods |
|---|---|
| Pointer | seekgetFilePointerskipBytes |
| Size | lengthsetLength |
| Bytes | read()read(byte[])readFullywrite(byte[]) |
| Typed values | readIntwriteIntreadLongwriteLongreadDoublewriteDouble |
| Text (avoid for files people read) | readLinewriteUTFwriteChars |
| NIO bridge | getChannel |
The modes are "r""rw""rws""rwd"writeUTF
Fixed-size records
When every record has the same size, record n starts at byte n × recordSize
| Field | Type | Offset in record | Bytes |
|---|---|---|---|
| id | int | 0 | 4 |
| name | UTF-8, padded with zero bytes | 4 | 20 |
| balance | long | 24 | 8 |
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.
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:
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Æ . The<U+FFFD> method steps back over UTF-8 continuation bytes (those starting with the bitsfit ) so the cut falls between characters.10 - 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.
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:
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 anddouble . The file length followed it to 22.short jumped over theskipBytes(8) . Near the end,long skipped only the 2 bytes that were left and returned 2; it never moves past the end, so check its return value.skipBytes(100) 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.seek(30) truncated the file and moved the pointer back to 6, because it was beyond the new end.setLength(6) extended it; the Javadoc leaves the content of the extension undefined.setLength(64)- At the end,
threwreadInt while the single-byteEOFException returned -1. Loops over typed records should checkread() rather than wait for an exception.getFilePointer() < length() threwseek(-1) .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
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:
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.
did oneget("ben") , oneseek and onereadInt , whatever the size of the file.readFully- 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
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.scan
Why small reads are slow, and what to do instead
Because RandomAccessFile
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):
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 andreadFully , 600,000 in all. It was the slowest by far.readLong - Reading each whole record with one
into areadFully and decoding it through abyte[32] made one call per record and was two to three times faster.ByteBuffer - For sequential reading, a
over aDataInputStream has the sameBufferedInputStream andreadInt methods but serves them from memory. It was several times faster again.readLong - A
reading 2,048 records per call was the fastest of all.FileChannel
So use RandomAccessFile
getChannel: one pointer, two APIs
getChannel()FileChannelRandomAccessFile
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:
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
moved the channel's position to 5, andraf.seek(5) moved the file pointer to 12, soch.position(12) returned the byte at 12, 'C'.raf.read() 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.ch.read(buf, 0)- Bytes written through the channel were immediately visible to the
, because neither side buffers.RandomAccessFile - Closing the
also closed the channel. Close either one, once.RandomAccessFile
Through the channel, an old RandomAccessFile
RandomAccessFile or something else?
| Need | Use |
|---|---|
| Read or update one fixed-size record | RandomAccessFileseekreadFullywrite |
| Values of very different sizes | Length-prefixed records appended to the file, with an index of offsets |
| Read every record in order | DataInputStreamBufferedInputStreamFileChannel |
| Several threads reading one file | FileChannel.read(buffer, position) |
| Random access to a large file as memory | FileChannel.map |
| The last lines of a text log | Seek near the end and decode; see |
| Replace text of the same byte length | Seek and write encoded bytes; see |
| Structured records with queries | An embedded database instead of a hand-made format |