Using RandomAccessFile objects in Java

Software

Coffee? Java? I know, it's cliche!

Messing around with some basic data files here using RandomAccessFile instead of reading in and writing data files sequentially.

import java.io.*;
public class TestRandomAccess {
  public static void main(String[] args) {
    try {
      RandomAccessFile raf = new RandomAccessFile("raf","rw");
      raf.writeInt(127);
      raf.writeDouble(2.718281828459045);
      raf.writeChars("Bird Bird Bird, the Bird is the Word");
      System.out.println(raf.length());
      raf.seek(4);
      System.out.println(raf.readDouble());
      System.out.println(raf.getFilePointer());
    }
    catch (Exception e) { System.err.println(e); }
  }
}

What's really cool is exporting a seemingly innocuous double (double length floating point number in Java) then reading back as an integer!

import java.io.*;
public class TestRandomAccess {
  public static void main(String[] args) {
    try {
      RandomAccessFile raf = new RandomAccessFile("raf","rw");
      raf.writeDouble(10.0);
      System.out.println(raf.readInt());
    }
    catch (Exception e) { System.err.println(e); }
  }
}

The result: 1076101120. Spiffy!

Author bio and support

Me!

Ruben Schade is a technical writer and IaaS engineer in Sydney, Australia who refers to himself in the third person in bios. Wait, not BIOS… my brain should be EFI by now.

The site is powered by Hugo, FreeBSD, and OpenZFS on OrionVM, everyone’s favourite cloud infrastructure provider.

If you found this post helpful or entertaining, you can shout me a coffee or buy some silly merch. Thanks!