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


Working with Random Access Files

The input and output 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. While still incredibly useful, sequential access files are a consequence of sequential medium such as magnetic tape. 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 other files and are compressed to conserve space. Zip files contain a "direntry" at the end that indicates where the various files contained within the zip file begin:

[PENDING: picture of zip file format here]

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 to extract. With a random access file, you only read the direntry 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.

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 InputStream or OutputStream. This has some disadvantages in that you can't apply the same filters to RandomAccessFiles that you can to streams. However, RandomAccessFile does implement the DataInput and DataOutput interfaces, so you could in fact design a filter that worked for either DataInput or DataOutput and it would work on (some) sequential access files (the ones that implemented DataInput or DataOutput) as well as any RandomAccessFile.

See Also

java.io.RandomAccessFile


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