Java Files  «Prev  Next»
Lesson 12 Positioning for random access reads and writes
ObjectiveInvestigate the methods available for positioning the file pointer in a random access file.

Positioning for Random Access Reads and Writes

The first argument to the constructor is the file you want to access. The second argument is the mode for access. The mode should be either the string literal "r" for read-only access or the string "rw" for read/write access. Java does not support write-only access. For example:

RandomAccessFile raf = new RandomAccessFile("random-access.html", "r");

An IllegalArgumentException is thrown if anything other than the strings "rw" or "r" is passed as the second argument to this constructor. A security exception is thrown if the security manager does not allow the requested file to be read. A security exception is also thrown if you request read/write access, but only read access is allowed. Security checks are made only when the object is constructed. It is assumed that the security manger's policy won't change while the program is running. Finally, an IOException is thrown if the operating system doesn't allow the file to be accessed or some other I/O problem occurs.

Java Lambdas and Parallel Streams

Miscellaneous methods:

The getFD() method simply returns the file descriptor for this file:
public final FileDescriptor getFD() throws IOException

The skipBytes() method attempts to reposition the file pointer n bytes further in the file from where it is now. It returns the number of bytes actually skipped, which may be less than n:
public int skipBytes(int n) throws IOException
The seek() method jumps to an absolute position in the file starting from 0, whereas skipBytes() moves n bytes past wherever the file pointer is now:
public void seek(long position) throws IOException

Finally, the close() method closes the file:
public native void close() throws IOException

Once the file is closed, it may not be read from.
However, a new RandomAccessFile object that refers to the same file can be created.

The getFilePointer() and seek() methods in the RandomAccessFile class allow you to determine and modify the position in the file at which reads and writes occur.

public native long getFilePointer() throws IOException
public native void seek(long pos) throws IOException
  1. Attempts to seek, or position the file pointer past the end of the file just move the file pointer to the end of the file.
  2. Attempts to write from the end of the file extend the file.
  3. Attempts to read from the end of the file throw an EOFException, which is a subclass of IOException.
You can determine the length of the file with the length() method.
public native long length() throws IOException