Java Reference ยท I/O and Files
The RandomAccessFile class
Reference for java.io.RandomAccessFile: jump to any byte with seek, read and write primitives in place, fixed-size records, and when to prefer NIO channels.
RandomAccessFile treats a file as a big array of bytes with a movable cursor called the file pointer. Unlike a stream, you can jump to any position with seek(), read from there, jump somewhere else and overwrite a few bytes in the middle, all without rewriting the rest of the file.
It implements both DataInput and DataOutput, so you can read and write int, long, double, boolean and modified-UTF-8 strings directly. That makes it a good fit for small fixed-record files and simple file formats. For new code that needs more control (memory mapping, locking, async I/O), see channels and ByteBuffer.
try (RandomAccessFile raf = new RandomAccessFile(file, "rw")) { raf.seek(8); int value = raf.readInt(); }
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.
Syntax
public class RandomAccessFile implements DataOutput, DataInput, Closeable RandomAccessFile(String name, String mode) throws FileNotFoundException RandomAccessFile(File file, String mode) throws FileNotFoundException
| Mode | Meaning |
|---|---|
"r" |
Read only. The file must exist. |
"rw" |
Read and write. The file is created if it does not exist. |
"rws" |
Like rw, and every change to content or metadata is written to the storage device synchronously. |
"rwd" |
Like rw, and every change to content is written synchronously (metadata may lag). |
| Member | Description |
|---|---|
void seek(long pos) |
Moves the file pointer to pos bytes from the start. |
long getFilePointer() |
The current position. |
long length() |
The file size in bytes. |
void setLength(long n) |
Truncates the file, or extends it with unspecified content. |
int read() / read(byte[]) |
Read a byte or fill an array; return -1 at the end. |
void readFully(byte[]) |
Reads exactly the array length or throws EOFException. |
readInt(), readLong(), readDouble(), readBoolean(), readUTF() |
Read big-endian primitives and strings. |
writeInt(int), writeLong(long), writeDouble(double), writeUTF(String), write(byte[]) |
Write at the pointer, advancing it. |
int skipBytes(int n) |
Moves forward at most n bytes without passing the end. |
FileChannel getChannel() |
The NIO channel sharing this file pointer. |
Throws: FileNotFoundException from the constructor, IllegalArgumentException for an invalid mode, IOException from reads and writes, EOFException from the readXxx methods at the end of the file.
Usage notes
- No buffering. Every
readInt()is several small reads, which makes loops over large files slow. Read a block into abyte[]orByteBufferwhen speed matters. - Seeking past the end is allowed. A later write extends the file and the gap has unspecified contents (usually zeros).
- Fixed-size records make index-to-offset math easy (
index * recordSize). Variable-length data, such aswriteUTFstrings, needs an index or a length prefix. - Byte order is always big-endian. Use
ByteBuffer.order(...)through the channel for little-endian formats. readUTF/writeUTFuse modified UTF-8 with a 2-byte length prefix and a 65,535-byte limit. They are not plain UTF-8.- Closing the object closes the file and its channel. Use try-with-resources.
- Not thread safe. The pointer is shared state, so concurrent
seekplusreadpairs interleave. Synchronize externally or useFileChannelpositional reads, which do not move the pointer. - Mode
ron a missing file throwsFileNotFoundException; moderwcreates it.