Java Reference
In-Depth Information
r. For reading only.
rw. For reading and writing.
rwd. For reading and writing, and in addition, causes all changes to the
file in memory to be written out to the file on the physical storage device
at the same time.
rws. Similar to rws, except the metadata is updated on the file as well.
This typically involves one more I/O operation than rwd mode.
A RandomAccessFile object contains an index referred to as the file pointer
that represents its current location in the file. The RandomAccessFile class con-
tains both read and write methods, with each operation occurring relative to
the current location of the file pointer. Some of the methods in the RandomAc-
cessFile class include:
public long getFilePointer(). Returns the current location of the file
pointer in bytes. This is often referred to as the offset since it represents
the distance in bytes from the beginning of the file.
public void seek(long offset). Moves the file pointer to the specified off-
set, measured in bytes relative to the beginning of the file.
public long length(). Returns the length of the file.
public final String readLine().
Reads the next line of text in the file.
The read and write methods of the RandomAccessFile class come in pairs,
such as:
readInt() and writeInt(). For reading and writing ints.
readLong() and writeLong(). For reading and writing longs.
readDouble() and writeDouble().
For reading and writing doubles.
readUTF() and writeUTF().
For reading and writing String objects.
There are similar read and write methods for the other Java primitive data
types. Study the following RandomAccessDemo program and try to deter-
mine what it does. You will have to follow along carefully, referring often to
the scores.html file in Figure 16.5. Figure 16.6 shows the generated file.
import java.io.*;
public class RandomAccessDemo
{
public static void main(String [] args)
{
try
{
RandomAccessFile file =
Search WWH ::




Custom Search