Code example for RandomAccessFile

Methods: readFullyreadIntseek

   * Reads the header. 
  private void readHeader() throws IOException {;
    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);;
   * Returns the Element for the given offset. 
  private Element readElement(int position) throws IOException {
    if (position == 0) return Element.NULL;;
    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. 
Stop searching for code, let great code find you!  Add Codota to your java IDE