Name

RandomAccessFile

Synopsis

This class allows you to read and write arbitrary bytes, text, and primitive Java data types from or to any specified location in a file. Because this class provides random, rather than sequential, access to files, it is neither a subclass of InputStream nor of OutputStream, but provides an entirely independent method for reading and writing data from or to files. RandomAccessFile implements the same interfaces as DataInputStream and DataOutputStream, and thus defines the same methods for reading and writing data as those classes do.

The seek( ) method provides random access to the file; it is used to select the position in the file where data should be read or written. The various read and write methods update this file position so that a sequence of read or write operations can be performed on a contiguous portion of the file without having to call the seek( ) method before each read or write.

The mode argument to the constructor methods should be “r” for a file that is to be read-only or “rw” for a file that is to be written (and perhaps read as well). In Java 1.4 and later, two other values for the mode argument are allowed as well. A mode of “rwd” opens the file for reading and writing, and requires that (if the file resides on a local filesystem) every update to the file content be written synchronously to the underlying file. The “rws” mode is similar, but requires synchronous updates to both the file’s content and its metadata (which includes ...

Get Java in a Nutshell, 5th Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.