Code example for RandomAccessFile

Methods: readFully, readInt, seek

0
 
  /** 
   * Reads the header. 
   */ 
  private void readHeader() throws IOException { 
    raf.seek(0);
    raf.readFully(buffer);
    fileLength = readInt(buffer, 0);
    elementCount = readInt(buffer, 4);
    int firstOffset = readInt(buffer, 8);
    int lastOffset = readInt(buffer, 12);
    first = readElement(firstOffset);
    last = readElement(lastOffset);
  } 
 
  /** 
   * Writes header atomically. The arguments contain the updated values. The 
   * class member fields should not have changed yet. This only updates the 
   * state in the file. It's up to the caller to update the class member 
   * variables *after* this call succeeds. Assumes segment writes are atomic 
   * in the underlying file system. 
   */ 
  private void writeHeader(int fileLength, int elementCount, int firstPosition,
      int lastPosition) throws IOException {
    writeInts(buffer, fileLength, elementCount, firstPosition, lastPosition);
    raf.seek(0);
    raf.write(buffer);
  } 
 
  /** 
   * Returns the Element for the given offset. 
   */ 
  private Element readElement(int position) throws IOException {
    if (position == 0) return Element.NULL;
    raf.seek(position);
    return new Element(position, raf.readInt());
  } 
 
  /** Atomically initializes a new file. */ 
  private static void initialize(File file) throws IOException {
    // Use a temp file so we don't leave a partially-initialized file.