The JavaTM Tutorial
Previous Page Lesson Contents Next Page Start of Tutorial > Start of Trail > Start of Lesson Search
Feedback Form

Trail: Essential Java Classes
Lesson: I/O

Working with Random Access Files

The input and output streams in this chapter so far have been sequential access streams — streams whose contents must be read or written sequentially. Although such streams are incredibly useful, they are a consequence of a sequential medium, such as paper and magnetic tape. A random access files, on the other hand, permit nonsequential, or random, access to a file's contents.

So why might you need random access files? Consider the archive format called ZIP. A ZIP archive contains files and is typically compressed to save space. It also contain a dir-entry at the end that indicates where the various files contained within the ZIP archive begin, as shown in the following figure.

A ZIP archive.

A ZIP archive.

Suppose that you want to extract a specific file from a ZIP archive. If you use a sequential access stream, you have to:
  1. Open the ZIP archive.
  2. Search through the ZIP archive until you located the file you wanted to extract.
  3. Extract the file.
  4. Close the ZIP archive.
Using this algorithm, on average, you'd have to read half the ZIP archive before finding the file that you wanted to extract. You can extract the same file from the ZIP archive more efficiently by using the seek feature of a random access file and following these steps: This algorithm is more efficient because you read only the dir-entry and the file that you want to extract.

The RandomAccessFile (in the API reference documentation) class in the java.io package implements a random access file.

Using Random Access Files

Unlike the input and output stream classes in java.io, RandomAccessFile is used for both reading and writing files. You create a RandomAccessFile object with different arguments depending on whether you intend to read or write.

RandomAccessFile isn't a stream class; it doesn't inherit from 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 if you design a filter that works for either DataInput or DataOutput, it will work on some sequential access files (the ones that implemented DataInput or DataOutput) as well as on any RandomAccessFile.


Previous Page Lesson Contents Next Page Start of Tutorial > Start of Trail > Start of Lesson Search
Feedback Form

Copyright 1995-2005 Sun Microsystems, Inc. All rights reserved.