RandomAccessFile Seek And Overwrite

Seek to fixed offsets in a RandomAccessFile to read records, append at the end, and overwrite fields in place.

JavaData Integrity

Code

snippet
import java.io.RandomAccessFile;
import java.nio.file.Files;
import java.nio.file.Path;

public class RandomAccessFileDemo {
    public static void main(String[] args) throws Exception {
        Path path = Files.createTempFile("raf-demo", ".bin");
        try (RandomAccessFile file = new RandomAccessFile(path.toFile(), "rw")) {
            // 顺序写两条记录:每条 int + double = 12 字节
            file.writeInt(101);
            file.writeDouble(91.5);
            file.writeInt(102);
            file.writeDouble(78.25);
            System.out.println("length: " + file.length());

            // 直接定位第二条记录
            file.seek(12);
            int id = file.readInt();
            double score = file.readDouble();
            System.out.println("second record: id=" + id + " score=" + score);

            // 跳到末尾追加第三条
            file.seek(file.length());
            file.writeInt(103);
            file.writeDouble(64.0);

            // 覆写第一条记录的分数
            file.seek(4);
            file.writeDouble(95.0);

            // 回读第一条记录验证覆盖结果
            file.seek(0);
            System.out.println("first record: id=" + file.readInt() + " score=" + file.readDouble());
            System.out.println("final length: " + file.length());
        } finally {
            Files.deleteIfExists(path);
        }
    }
}

How it works

RandomAccessFile Seek And Overwrite reduces to the class RandomAccessFileDemo.

Resources are declared in a try-with-resources header, so they close on every exit path; the finally block in this method runs separately for its own cleanup.

Putting it to use

Running the file prints labeled results such as length:, second record: id=, first record: id= — each operation’s effect is visible in the output.

Core lines

Path path = Files.createTempFile("raf-demo", ".bin");
double score = file.readDouble();
Files.deleteIfExists(path);

Interactive Tools for This Topic

FAQ

What does RandomAccessFile Seek And Overwrite print when run?
Execute the whole file; each printed line is prefixed with a label like `length:`, `second record: id=`, `first record: id=`.