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


Using Random Access Files

The RandomAccessFile class implements both the DataInput and DataOutput interfaces and therefore can be used for both reading and writing. RandomAccessFiles are similar to FileInputStream and FileOutputStream in that you specify a file on the native file system to open when you create it. You can do this with a String specifying the name of the file or a File(in the API reference documentation)object. Also, when you create a RandomAccessFile, you must indicate whether you will be reading, or reading and writing the file. This line of Java code creates a RandomAccessFile to read the file named farrago.txt:
new RandomAccessFile("farrago.txt", "r");
And this one opens the same file for reading and writing (you have to be able to read a file in order to write it):
new RandomAccessFile("farrago.txt", "rw");
After the file has been opened, you can use the common readXXX() or writeXXX() methods to perform I/O on the file.

RandomAccessFile supports the notion of a file pointer. The file pointer indicates the current location in the file. When the file is first created the file pointer is positioned at the beginning of the file. Calls to readXXX() and writeXXX() methods adjust the file pointer according to the number of bytes read or written.

[PENDING: picture of file pointer]

In addition to the normal file I/O methods that implicitly move the file pointer when the operation occurs, RandomAccessFile contains three methods for explicitly manipulating the file's file pointer.

skipBytes()
moves the file pointer forward the specified number of bytes.
seek()
positions the file pointer just before the specified byte.
getFilePointer()
returns the current location of the file pointer (in bytes)
[PENDING: should really write an example for RAFs, maybe do a miniature zip file implementation]


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