Java Files  «Prev 


Random Access Files

In record-oriented applications like databases, the actual data may be indexed, and you would use the index to determine where in the file to find the record you need to read or write.
While you could do this by constantly opening and closing the file and skipping to the point where you needed to read, this is far from efficient. Writes are even worse since you would need to read and rewrite the entire file, even to change just a single byte of data.
Random access files permit nonsequential, or random, access to a file's contents. To access a file randomly, you open the file, seek a particular location, and read from or write to that file.
This functionality is possible with the SeekableByteChannel interface. The SeekableByteChannel interface extends channel I/O with the notion of a current position. Methods enable you to set or query the position, and you can then read the data from, or write the data to, that location. The API consists of a few, easy to use, methods:
  1. position: Returns the channel's current position
  2. position(long): Sets the channel's position
  3. read(ByteBuffer): Reads bytes into the buffer from the channel
  4. write(ByteBuffer): Writes bytes from the buffer to the channel
  5. truncate(long): Truncates the file (or other entity) connected to the channel

In Java, random file access is performed through the java.io.RandomAccessFile class, which is not a subclass of java.io.File:
public class RandomAccessFile extends Object implements DataInput, DataOutput

Among other differences between File objects and RandomAccessFile objects, the RandomAccessFile constructors actually open the file in question and throw an IOException if it does not exist:
public RandomAccessFile(String filename, String mode) throws
FileNotFoundException

public RandomAccessFile(File file, String mode) throws IOException
  1. The first argument to the constructor is the file you want to access.
  2. 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.