Input and Output Streams |
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 nonsequential, or random, access to the contents of a file.So why might you need random access files. Consider the archive format known as "zip". Zip archives contain files and are typically compressed to save space. Zip archives also contain a "dir-entry" at the end that indicates where the various files contained within the zip archive begin:
Now suppose that you wanted to extract a specific file from a zip archive. If you were to use a sequential access stream, you'd have to do the following:
On average, using this algorithm, 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 using the seek feature of a random access file:
- Open the zip archive.
- Search through the zip archive until you located the file you wanted to extract.
- Extract the file.
- Close the zip archive.
This algorithm is more efficient because you only read the dir-entry and the file that you want to extract.
- Open the zip archive.
- Seek to the dir-entry and locate the entry for the file you want to extract from the zip archive.
- Seek (backwards) within the zip archive to the position of the file to extract.
- Extract the file.
- Close the zip archive.
The RandomAccessFile 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 the RandomAccessFile with different arguments depending on whether you intend to read or write.Writing Filters for Random Access Files
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
Input and Output Streams |