Java Reference
In-Depth Information
Display 10.21
Some Methods of the Class
RandomAccessFile
(part 3 of 3)
public final int
readInt)
throws
IOException
Reads an
int
value from the file and returns that value. If an attempt is made to read beyond the
end of the file, an
EOFException
is thrown.
public final long
readLong()
throws
IOException
Reads a
long
value from the file and returns that value. If an attempt is made to read beyond the
end of the file, an
EOFException
is thrown.
public final double
readDouble()
throws
IOException
Reads a
double
value from the file and returns that value. If an attempt is made to read beyond
the end of the file, an
EOFException
is thrown.
public final float
readFloat()
throws
IOException
Reads a
float
value from the file and returns that value. If an attempt is made to read beyond
the end of the file, an
EOFException
is thrown.
public final char
readChar()
throws
IOException
Reads a
char
value from the file and returns that value. If an attempt is made to read beyond the
end of the file, an
EOFException
is thrown.
public final boolean
readBoolean()
throws
IOException
Reads a
boolean
value from the file and returns that value. If an attempt is made to read beyond
the end of the file, an
EOFException
is thrown.
public final
String readUTF()
throws
IOException
Reads a
String
value from the file and returns that value. If an attempt is made to read beyond
the end of the file, an
EOFException
is thrown.
readUTF
, and so on. However, the class
RandomAccessFile
does not have the
methods
writeObject
or
readObject
. The most important methods of the class
RandomAccessFile
are given in Display 10.21. A demonstration program for random
access files is given in Display 10.22 .
The constructor for
RandomAccessFile
takes either a string name for the file or
an object of the class
File
as its first argument. The second argument must be one of
the four strings
"rw"
,
"r"
, and two modes we do not discuss in this topic,
"rws"
and
"rwd"
. The string
"rw"
means your code can both read and write to the file after it is
open. The string
"r"
means your code can read from the file but cannot write to the file.
If the file already exists, then when it is opened, the length is not reset to
0
, but the
file pointer will be positioned at the start of the file, which is what you would expect at
least for
"r"
. If the length of the file is not what you want, you can change it with the
method
setLength
. In particular, you can use
setLength
to empty the file.
opening a file