📜 File Access Modes in RandomAccessFile
1. "r" — Read-only
- Read operations only.
- No writing allowed.
- File must exist, or you’ll get
FileNotFoundException.
🔹 Use Case: Inspect a file without modifying it.
RandomAccessFile raf = new RandomAccessFile("input.txt", "r");
2. "rw" — Read and Write
- Allows both reading and writing.
- File will be created if it doesn’t exist.
- Writes may be buffered (not immediately flushed to disk).
🔹 Use Case: Modify or append data to files.
RandomAccessFile raf = new RandomAccessFile("data.bin", "rw");
. "rws" — Read, Write, Sync metadata & content
- Like
"rw"but synchronously updates:- File content
- File metadata (like timestamps)
- More durable (good for logs), but slower due to forced disk sync.
🔹 Use Case: Critical logs or journaling systems.
RandomAccessFile raf = new RandomAccessFile("log.txt", "rws");
4. "rwd" — Read, Write, Sync content only
- Like
"rw"but only synchronously writes file content (not metadata). - Slightly faster than
"rws"while still safe for data integrity.
🔹 Use Case: When you care about the data being saved, not file attributes.
RandomAccessFile raf = new RandomAccessFile("important.txt", "rwd");
🧵 TL;DR Table
| Mode | Read | Write | Auto-create file | Sync content? | Sync metadata? | Use Case |
|---|---|---|---|---|---|---|
"r" | ✅ | ❌ | ❌ | ❌ | ❌ | Read-only access |
"rw" | ✅ | ✅ | ✅ | ❌ | ❌ | General read/write |
"rws" | ✅ | ✅ | ✅ | ✅ | ✅ | Durable writes + metadata |
"rwd" | ✅ | ✅ | ✅ | ✅ | ❌ | Safe writes (faster than rws) |