Previous | Next | Trail Map | Writing Java Programs | Input and Output Streams


Working with Random Access Files

The input and streams that you've been learning about so far in this lesson have been sequential access streams--streams whose contents must be read or written sequentially. Sequential access files are leftovers from the days of magnetic tape and other naturally sequential medium. Random access files, on the other hand, permit non-sequential, or random, access to the contents of a file.

Random access files are useful for many different applications. One specific example of a good use of random access files are zip files. Zip files contain many other files and are compressed to conserve space. Zip files contain a directory at the end that indicates where the various contained files begin:

[PENDING: picture]

An efficient way to extract a particular file from within a zip file is with a random access file:

With a sequential access file, on average you'd have to read half the zip file before finding the file that you wanted. With a random access file, you only read the directory and the file that you need.

The RandomAccessFile class in the java.io package implements a random access file.

Using Random Access Files

Unlike the input and output streams in java.io, RandomAccessFile is used for both reading and writing files. You create the RandomAccessFile with different arguments depending on whether you intend to read or write. This is similar to the way files work on Unix.

Writing Filters for RandomAccessFiles and DataInput/DataOutput

RandomAccessFile is somewhat disconnected from the input and output streams in java.io--it doesn't inherit from the same base class. This has some disadvantages in that you can't apply the same filters to RandomAccessFiles that you can to streams. However, RandomAccessFile does implement DataInput and DataOutput, so you could in fact design a filter that worked for either DataInput or DataOutput and it would work on (some) sequential access files and as well as any RandomAccessFile.

See Also

java.io.RandomAccessFile


Previous | Next | Trail Map | Writing Java Programs | Input and Output Streams