The RandomAccessFile
class implements both the DataInput
and DataOutput
interfaces and therefore can be used for both reading and writing.
RandomAccessFile
is 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 filename or a
File object. When you create a RandomAccessFile
, you must indicate
whether you will be just reading the file or also writing to it. (You have to
be able to read a file in order to write it.) The
following 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 both reading and writing:
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 0, indicating the beginning of the file. Calls
to the readXXX
and writeXXX
methods adjust the
file pointer by the number of bytes read or written.
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 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 byte location of the file pointer.