Java RandomAccessFile: Seeking and Fixed-Size Records
Read and write anywhere in a file with Java's RandomAccessFile: the r, rw, rws and rwd modes, the file pointer, seek, getFilePointer, length and setLength, storing fixed-size records, reading records in any order, updating a record in place, and when FileChannel is the better choice.
kvi5hnuCode Sprout team member7 min readOn this page
Input and output streams are sequential: you read from the beginning to the end, and you write by adding to the end. A disk file allows more. You can jump to any byte position and read or write there. Network connections and pipes can't do that, but files can, and RandomAccessFile gives you access to that capability. It's the natural tool for files of fixed-size records, where you can calculate exactly where record number n starts.
Opening a random-access file
The constructor takes a file (a name or a File) and a mode string:
var in = new RandomAccessFile("employee.dat", "r"); // read only
var inOut = new RandomAccessFile("employee.dat", "rw"); // read and write
| Mode | Meaning |
|---|---|
"r" | read only; the file must exist; any write throws IOException |
"rw" | read and write; the file is created if it doesn't exist |
"rws" | like "rw", and every update to the content and metadata is written synchronously to the storage device |
"rwd" | like "rw", and every update to the content is written synchronously |
The synchronous modes are much slower, but data written before a crash or power loss is not lost. Opening an existing file in "rw" mode does not truncate it, unlike FileOutputStream. The existing bytes stay until you overwrite them.
The file pointer
A random-access file has a file pointer, the position of the next byte to be read or written. It starts at 0 and advances as you read or write.
seek(long pos)moves the file pointer to byte positionpos. Seeking past the end is allowed. Writing there extends the file, and the gap's contents are unspecified (typically zeros).getFilePointer()returns the current position.length()returns the file size in bytes.setLength(long newLength)truncates or extends the file.
RandomAccessFile implements both DataInput and DataOutput, so you read and write with the methods from the previous article: readInt, writeDouble, readFully and so on.
Fixed-size records
The demo stores employees as records of exactly 100 bytes:
| Field | Encoding | Bytes |
|---|---|---|
| name | 40 chars, padded with zeros | 80 |
| salary | double | 8 |
| hire year, month, day | 3 × int | 12 |
With a fixed size, record n (counting from 0) starts at byte n * RECORD_SIZE, and the number of records is the file length divided by the record size:
in.seek((long) n * RECORD_SIZE);
Employee e = readData(in);
int count = (int) (in.length() / RECORD_SIZE);
Note the cast to long before the multiplication. In a large file, n * RECORD_SIZE computed in int arithmetic overflows past 2 GB.
The numbers have fixed sizes anyway. Strings need help: the demo writes a name as exactly 40 chars, padding with zero characters, and reads up to the first zero and then skips the rest of the field:
static void writeFixedString(String s, int size, DataOutput out) throws IOException {
for (int i = 0; i < size; i++)
out.writeChar(i < s.length() ? s.charAt(i) : 0);
}
static String readFixedString(int size, DataInput in) throws IOException {
var b = new StringBuilder(size);
int i = 0;
while (i < size) {
char ch = in.readChar();
i++;
if (ch == 0) break;
b.append(ch);
}
in.skipBytes(2 * (size - i));
return b.toString();
}
A name longer than 40 characters is silently cut off, which is the price of fixed sizes. Make fields big enough, and validate input before writing. A cut could also split a surrogate pair. A more compact alternative is a fixed-size field of UTF-8 bytes with a length byte in front.
Updating in place
To change a record, seek to its start, read it, seek back to the same position, and write the new version. After the read, the file pointer has moved on to the next record, so without the second seek you'd overwrite the wrong one:
inOut.seek(pos);
Employee e = readData(inOut);
inOut.seek(pos);
writeData(inOut, e.withRaise());
You can even update a single field. The salary of record n starts 80 bytes into the record, at n * RECORD_SIZE + 80. To append a record, seek to length() and write. To delete records at the end, use setLength. Deleting from the middle means moving every later record down, or, more commonly, marking the record as deleted with a flag field and reusing its slot later.
A complete example
The demo writes three records with a DataOutputStream, reads them back in reverse order with RandomAccessFile, updates one record and one field in place, appends a record and finally truncates the file.
import java.io.*;
import java.nio.file.*;
import java.time.LocalDate;
import java.util.*;
public class Solution {
record Employee(String name, double salary, LocalDate startDate) {}
static final int NAME_SIZE = 40; // chars
static final int RECORD_SIZE = 2 * NAME_SIZE + 8 + 4 + 4 + 4; // 100 bytes
static void writeFixedString(String s, int size, DataOutput out) throws IOException {
for (int i = 0; i < size; i++)
out.writeChar(i < s.length() ? s.charAt(i) : 0);
}
static String readFixedString(int size, DataInput in) throws IOException {
var b = new StringBuilder(size);
int i = 0;
while (i < size) {
char ch = in.readChar();
i++;
if (ch == 0) break;
b.append(ch);
}
in.skipBytes(2 * (size - i));
return b.toString();
}
static void writeData(DataOutput out, Employee e) throws IOException {
writeFixedString(e.name(), NAME_SIZE, out);
out.writeDouble(e.salary());
out.writeInt(e.startDate().getYear());
out.writeInt(e.startDate().getMonthValue());
out.writeInt(e.startDate().getDayOfMonth());
}
static Employee readData(DataInput in) throws IOException {
String name = readFixedString(NAME_SIZE, in);
double salary = in.readDouble();
int y = in.readInt(), m = in.readInt(), d = in.readInt();
return new Employee(name, salary, LocalDate.of(y, m, d));
}
public static void main(String[] args) throws IOException {
Path file = Files.createTempFile("employee", ".dat");
List<Employee> staff = List.of(
new Employee("Priya Nair", 68000, LocalDate.of(2016, 4, 11)),
new Employee("Omar Haddad", 52000, LocalDate.of(2019, 9, 2)),
new Employee("Lena Fischer", 46000, LocalDate.of(2021, 6, 21)));
// write all records sequentially
try (var out = new DataOutputStream(new BufferedOutputStream(Files.newOutputStream(file)))) {
for (Employee e : staff) writeData(out, e);
}
System.out.println("file length: " + Files.size(file) + " bytes = " + Files.size(file) / RECORD_SIZE + " records");
// read them in reverse order
try (var in = new RandomAccessFile(file.toFile(), "r")) {
int n = (int) (in.length() / RECORD_SIZE);
for (int i = n - 1; i >= 0; i--) {
in.seek((long) i * RECORD_SIZE);
System.out.println("record " + i + ": " + readData(in));
}
System.out.println("file pointer after the first record: " + in.getFilePointer());
}
// update one record in place: give Omar a raise
try (var inOut = new RandomAccessFile(file.toFile(), "rw")) {
long pos = 1L * RECORD_SIZE;
inOut.seek(pos);
Employee omar = readData(inOut);
inOut.seek(pos); // back to the start of the record before writing
writeData(inOut, new Employee(omar.name(), omar.salary() + 5000, omar.startDate()));
// patch a single field: Lena's salary sits 80 bytes into record 2
inOut.seek(2L * RECORD_SIZE + 2 * NAME_SIZE);
inOut.writeDouble(51000);
// append a record at the end
inOut.seek(inOut.length());
writeData(inOut, new Employee("Ines Ortega", 59000, LocalDate.of(2023, 1, 9)));
System.out.println("records after appending: " + inOut.length() / RECORD_SIZE);
}
try (var in = new RandomAccessFile(file.toFile(), "r")) {
for (int i = 0; i < in.length() / RECORD_SIZE; i++)
System.out.println(readData(in));
}
// truncate the file to two records
try (var inOut = new RandomAccessFile(file.toFile(), "rw")) {
inOut.setLength(2L * RECORD_SIZE);
System.out.println("after setLength: " + inOut.length() / RECORD_SIZE + " records");
}
// names longer than the field are cut off
var bout = new ByteArrayOutputStream();
writeFixedString("A".repeat(50), NAME_SIZE, new DataOutputStream(bout));
String back = readFixedString(NAME_SIZE, new DataInputStream(new ByteArrayInputStream(bout.toByteArray())));
System.out.println("a 50-char name is stored as " + back.length() + " chars");
// "r" mode can't write
try (var in = new RandomAccessFile(file.toFile(), "r")) {
in.writeInt(1);
} catch (IOException e) {
System.out.println("writing in \"r\" mode: " + e.getClass().getSimpleName());
}
Files.delete(file);
}
}
file length: 300 bytes = 3 records
record 2: Employee[name=Lena Fischer, salary=46000.0, startDate=2021-06-21]
record 1: Employee[name=Omar Haddad, salary=52000.0, startDate=2019-09-02]
record 0: Employee[name=Priya Nair, salary=68000.0, startDate=2016-04-11]
file pointer after the first record: 100
records after appending: 4
Employee[name=Priya Nair, salary=68000.0, startDate=2016-04-11]
Employee[name=Omar Haddad, salary=57000.0, startDate=2019-09-02]
Employee[name=Lena Fischer, salary=51000.0, startDate=2021-06-21]
Employee[name=Ines Ortega, salary=59000.0, startDate=2023-01-09]
after setLength: 2 records
a 50-char name is stored as 40 chars
writing in "r" mode: IOException
Common questions
How do I read the last lines of a large log file, like tail?
Open it with RandomAccessFile in "r" mode, seek to a little before the end (for example length() - 64 * 1024, but not below 0), read that block with readFully, and split it into lines. Repeat with a larger block if you need more lines. This avoids reading gigabytes just to see the end.
Is RandomAccessFile thread-safe?
No. It has one file pointer, and a seek in one thread followed by a read in another mixes up positions. Give each thread its own RandomAccessFile, or use a FileChannel, whose positional read(buffer, position) and write(buffer, position) methods do not use the shared position and are safe to call concurrently.
RandomAccessFile, FileChannel or memory mapping: which should I use?
RandomAccessFile is fine for simple record files. FileChannel is the modern choice: buffer-based, positional, lockable, and thread-safe for positional I/O. Memory mapping (article 29) is fastest when a large file is accessed often at random places. A database is better than all three once you need indexes, concurrency or transactions.
What does "rws" cost?
Every write waits until the data has reached the storage device, which can make writing hundreds of times slower. A common compromise is "rw" plus an explicit getChannel().force(true) at points where durability matters, such as after completing a transaction.
Does RandomAccessFile work with files larger than 2 GB?
Yes. Positions and lengths are long values, so files can be far larger than 2 GB. Only the arithmetic in your own code has to use long, as the article explains.
API reference
java.io.RandomAccessFile (implements DataInput, DataOutput and Closeable)
| Method | Description |
|---|---|
RandomAccessFile(String file, String mode), RandomAccessFile(File file, String mode) | opens a file in mode "r", "rw", "rws" or "rwd" |
long getFilePointer() | the current position of the file pointer |
void seek(long pos) | moves the file pointer to pos bytes from the start |
long length() | the file length in bytes |
void setLength(long newLength) | truncates or extends the file |
int read(byte[] b), void readFully(byte[] b), void write(byte[] b) | raw byte access |
FileChannel getChannel() | the file channel for this file |
Summary
RandomAccessFilereads and writes at any position in a file. Open it with"r","rw", or the synchronous"rws"and"rwd"modes."rw"doesn't truncate existing files.- The file pointer marks the next position.
seek,getFilePointer,lengthandsetLengthcontrol it and the file size. - It implements
DataInputandDataOutput, so you usereadInt,writeDoubleand friends. - With fixed-size records, record n starts at
n * RECORD_SIZE. Compute positions inlongarithmetic. - To update in place, seek back to the start of the record before writing. Strings need fixed-size fields, and longer values are cut off.
RandomAccessFileisn't buffered. Read whole records at a time, or useFileChannelwithByteBuffers.
Practice Questions
A file holds 64-byte records. Which call positions the file pointer at the start of record number 10, counting from 0?
raf.seek(10L * 64);, which is byte 640. Using a long literal keeps the arithmetic safe for large record numbers.
You read a record and then write the updated record, but the file now has the old record unchanged and the next record overwritten. What happened?
Reading moved the file pointer to the end of the record, so the write landed on the following record. Call seek(recordStart) again between the read and the write.
How is opening a file with new RandomAccessFile(f, "rw") different from new FileOutputStream(f)?
FileOutputStream truncates an existing file to zero length, unless you pass append = true. RandomAccessFile in "rw" mode keeps the contents, and you overwrite only the bytes you write.
When would you choose "rwd" mode, and what does it cost?
When each update must survive a crash or power failure immediately, for example in a simple transaction log. Every write waits until the data reaches the storage device, which can make writing orders of magnitude slower.
How do you remove the last three records from a file of RECORD_SIZE-byte records?
raf.setLength(raf.length() - 3L * RECORD_SIZE);. setLength truncates the file, discarding everything past the new length.
Previous: Java DataInput and DataOutput: Reading and Writing Binary Data
Next: Java ZIP Archives: ZipInputStream, ZipOutputStream and ZIP File Systems
Related reading
- Java DataInput and DataOutput: Reading and Writing Binary Data
- Java Character Encodings: UTF-8, Charsets and the Default Encoding
- Java Text Input and Output: PrintWriter, BufferedReader and Saving Objects as Text
- Java I/O Filters: Buffered, Data and Pushback Streams
- Java I/O Streams: Reading and Writing Bytes

More in Core Java II
FFM Upcalls, Variadic Functions and errno
Advanced FFM calls: passing Java code to C as function pointers with upcall stubs, binding objects and lambdas, calling variadic functions such as printf, capturing errno and GetLastError, and a C library that calls back into Java. The final article of the course.
Calling Foreign Functions: Linker, Symbol Lookup, Downcalls and jextract
Calling C functions from pure Java with the FFM API: the native linker, default, library and loader symbol lookups, function descriptors, downcall handles, invokeExact, pointers and NULL, struct results, critical calls, enabling native access, and generating bindings with jextract.
FFM Memory Layouts: Structs, Unions, Sequences and Var Handles
Describing C data with FFM memory layouts: value layouts and C types, struct and union layouts, alignment and padding, sequences, layout paths, var handles with base offsets, offset and slice handles, pointers with target layouts, and atomic access modes.
Foreign Function and Memory API: Arenas and Memory Segments
Getting started with the FFM API (final since Java 22): a first foreign call, confined, shared, automatic and global arenas, native and heap memory segments, reading and writing values, C strings and arrays, alignment and byte order, slices, copies, allocators, and memory-mapped files.
Discussion
Sign in to ask a question or share what you learned.