Java Files  «Prev  Next»

Lesson 11Working with RandomAccessFile
ObjectiveExplain how to use RandomAccessFile for random read/write access in Java

RandomAccessFile in Java

Most input/output streams in Java read or write sequentially from start to end. Sometimes, however, you need direct access to a specific location in a file—for example, updating a record in a database-like file or reading a fixed-length record from the middle of a large file. RandomAccessFile provides this capability: it allows both reading and writing at arbitrary byte positions without reopening the file.

Key Characteristics

Class Definition


  public class RandomAccessFile
      extends Object
      implements DataInput, DataOutput, Closeable
  

Constructors


  public RandomAccessFile(String filename, String mode) 
      throws FileNotFoundException

  public RandomAccessFile(File file, String mode) 
      throws IOException
  

The constructor immediately opens the file. If the file does not exist (and cannot be created in write mode), an exception is thrown.

Common Methods

Reading

Writing

Pointer Control

Other



Example: Updating a Record


  try (RandomAccessFile raf = new RandomAccessFile("records.dat", "rw")) {
      long recordSize = 128; // fixed-length records
      int recordNumber = 10;

      // Move to start of the 10th record
      raf.seek(recordNumber * recordSize);

      // Read an integer field
      int id = raf.readInt();

      // Update a value
      raf.writeUTF("Updated Name");
  }
  

Exceptions

EOFException is thrown if end-of-file is reached unexpectedly (e.g., when using readFully()). Other IOExceptions occur if the file is closed or another I/O error happens.

Notes and Best Practices


SEMrush Software