Home : Course Map : Chapter 9 : Java : Advanced :
Random Access in a File
Course Map
Chapter 9

Console I/O
  Text Output 
     Demo 1

     Demo 2

  Tex 2t Input
     Demo 3

Demo 4
File Class
  File I/O
  File Output-Text
     Demo 5

  Formatter to File
     Demo 6

  File Input - Text
    Demo 7

  Scanner - Files
     Demo 8

  File I/O - Binary
     Demo 9
   Demo 10
File Chooser Dialog
  Demo 11

Character Codes
  Demo 12
Object I/O
Types to Bytes
Stream Filters
Other I/O Topics

Character I/O
  Demo 1   Demo 2
Random Access
  Demo 3
ZIP/GZIP Streams
  Demo 4
Piped Streams
  Demo 5
NIO Framework
More NIO
  Demo 6

     About JavaTech
     Codes List
     Topic Index
     Course Guide
     What's New

The streams discussed in Chapter 9: Java dealt with data going in one direction (in or out) and with data read or written sequentially. A common requirement, however, is to access a file in a way that lets you both read and write to it and also to move to any point within the file to carry out those operations. The RandomAccessFile class allows just for this type of access to any random place with in the file.

The RandomAccessFile object provides a file pointer that acts as a index to indicate where in the file a read or write operation begins. In that sense, a RandomAccessFile object acts like an array representing the bytes of the file. One difference is that a write operation that goes past the end of the array will append the data as if the array had been automatically extended. Attempts to read past the end of the file will, however, for many of the read methods result in an EOFException.

The class has two constructors, one of which uses a File object to specify the file and the other a string name for the file. A second argument determines the access mode for the file. A random access file object can be created just for reading as follows:

RandomAccessFile file_readonly = new RandomAccessFile ("data.txt", "r");

A file for both reading and writing could be created like this:

File my_file = getMyFile();
RandomAccessFile file_readonly = new RandomAccessFile (my_file, "rw");

If the file does not exist, the readonly mode would result in a IOException. For the read-write mode, the file will be created if it does not exist.

See the class specifications of RandomAccessFile for a long list of available read and write methods. (The class implements the DataInput and DataOutput interfaces just like DataInputStream and DataOutputStream, resp.) There is also the method

void seek (long pos)

that allows you to specify the index for where read and write operations will start. The method

long getFilePointer ()

which returns the current position of the pointer. And the method

int skipBytes (int n)

jumps the pointer by n bytes from its current location.

Demo of RandomAccessFile

The following simple demo program illustrates the basics of working with the RandomAccessFile. From the command line you specify where in a file of integer numbers where you want a number to be written.


import java.io.*;

  * Use RandomAccessFile to write a number into a file.
  * Command line specifies the single integer value to
  * write, the position in the file where it is to be
  * written, and the name of the file, which should contain
  * a series of integer values. The position will be in
  * terms of integer values, not bytes. The file will be
  * created if it doesn't exist already.
public class RandomFileTest  {

  public static void main (String [] args) {

    int value = 0;
    long position = 0;

    if (args.length < 3) {
      System.out.println ("Usage: java RandomFileTest value position filename");

    try {
      value = Integer.parseInt (args[0]);
    catch (NumberFormatException nfe) {
      System.out.println ("Bad number value!");
      System.out.println ("Usage: java RandomFileTest value position filename");
      System.exit (0);

    // Check
    try {
      position = Long.parseLong (args[1]);
      // Treat number as absolute value.
      if (position < 0) position = -position;
      position = 4*position; // 4 bytes per integer.
    catch (NumberFormatException nfe) {
      System.out.println ("Bad position value!");
      System.out.println ("Usage: java RandomFileTest value position filename");
      System.exit (0);

    RandomAccessFile file = null;
    try {
      file = new RandomAccessFile (args[2], "rw");
    catch (FileNotFoundException ffe) {
      System.out.println("File not found. Will create it.");

    try {

      // Append if position beyond the end of the file.
      if (position > 0 && position >= file.length ()) {
        position = file.length ();

      // Move to the desired position and write the number.
      file.seek (position);
      file.writeInt (value);

      // Move back to the start of the file and print it out
      file.seek (0);
      int num_entries = (int)(file.length () / 4);
      for (int i=0; i < num_entries; i++) {
        System.out.printf ("%10d", file.readInt ());
        if (i != 0 && (i%6) == 0) System.out.println();

    catch (IOException ioe) {
      System.out.println ("IO Exception = " + ioe);
  } // main

} // RandomFileTest


References & Web Resources

Most recent update: August 19, 2005

Histogram I/O
Hist I/O - Get/Set
  Demo 1
Hist I/O - Objects
  Demo 2
  Demo 3
Filtering Data
  Demo 4

Physics Model
Simulation Design
Physics Simulator
  Demo 1
Experiment Design
Experiment Sim.
  Demo 2
Expt. + Analysis
  Demo 3

  Part I Part II Part III
Java Core 1  2  3  4  5  6  7  8  9  10  11  12 13 14 15 16 17
18 19 20
22 23 24

1  2  3  4  5  6  7  8  9  10  11  12

Tech 1  2  3  4  5  6  7  8  9  10  11  12
Physics 1  2  3  4  5  6  7  8  9  10  11  12

Java is a trademark of Sun Microsystems, Inc.