Java.Streams.What do you know about RandomAccessFile?

📘 What is RandomAccessFile?

  • It’s part of java.io.
  • Supports both reading and writing.
  • Allows you to move the file pointer to read/write anywhere (random access).
  • Acts like a combination of DataInputStream + DataOutputStream + file pointer control.

🔧 Constructor

RandomAccessFile(File file, String mode)
RandomAccessFile(String name, String mode)

📜 Modes:

  • "r" → read-only
  • "rw" → read + write
  • "rws" → read/write with synchronous updates to file & metadata
  • "rwd" → read/write with synchronous updates to file data only

🔑 Key Features & Methods

MethodDescription
readXxx()Read primitives: readInt(), readDouble(), readUTF()
writeXxx()Write primitives: writeInt(), writeBoolean(), writeUTF()
seek(long pos)Move the file pointer to position pos
getFilePointer()Returns current file pointer position
length()Returns the total file length in bytes
setLength(long newLength)Truncates or extends the file

✅ Example: Read and Write with RandomAccessFile

import java.io.RandomAccessFile;

public class RandomAccessDemo {
    public static void main(String[] args) throws Exception {
        RandomAccessFile raf = new RandomAccessFile("data.bin", "rw");

        // Write data
        raf.writeInt(42);
        raf.writeUTF("Hello, Stanley!");

        // Move to the beginning
        raf.seek(0);

        // Read data
        int number = raf.readInt();
        String message = raf.readUTF();

        System.out.println("Number: " + number);
        System.out.println("Message: " + message);

        raf.close();
    }
}

📦 Use Cases

Use CaseWhy RandomAccessFile
Large file manipulationRead/write without loading whole file
Fixed-size record storageAccess specific record by position
Database/index structuresJump to index offsets directly
Append at specific offsetSeek to the end or anywhere

⚠️ Caveats

  • Not buffered (low-level)
  • Not thread-safe unless synchronized externally
  • Should be closed manually (no AutoCloseable until Java 7)

🧵 TL;DR

FeatureRandomAccessFile
Supports read/write?✅ Yes
Move to specific position?✅ Yes (seek())
Good for?File editing, logs, databases
Stream-based?❌ No (it’s a direct file API)
Char encoding?❌ Manual (not charset-aware like Reader)
This entry was posted in Без рубрики. Bookmark the permalink.

Leave a Reply

Your email address will not be published.