Java Reference
In-Depth Information
RandomAccessFile
Filescanbecreatedand/oropenedfor
random access
inwhichwriteandreadoperations
can occur until the file is closed. Java supports this random access via its concrete
java.io.RandomAccessFile
class.
RandomAccessFile
declares the following constructors:
•
RandomAccessFile(File file, String mode)
createsandopens
anewfileifitdoesn'texist,oropensanexistingfile.Thefileisidentified by
file
's abstract pathname and is created and/or opened according to
mode
.
•
RandomAccessFile(String pathname, String mode)
creates
andopensanewfileifitdoesn'texist,oropensanexistingfile.Thefileisiden-
tified by
pathname
and is created and/or opened according to
mode
.
Eitherconstructor's
mode
argumentmustbeoneof
"r"
,
"rw"
,
"rws"
,or
"rwd"
;
otherwise,theconstructorthrows
IllegalArgumentException
.Thesestringlit-
erals have the following meanings:
•
"r"
informs the constructor to open an existing file for reading only. Any at-
tempt to write to the file results in a thrown instance of the
IOException
class.
•
"rw"
informstheconstructortocreateandopenanewfilewhen itdoesn'tex-
ist for reading and writing, or open an existing file for reading and writing.
•
"rwd"
informs the constructor to create and open a new file when it doesn't
exist for reading and writing, or open an existing file for reading and writing.
Furthermore,eachupdatetothefile'scontentmustbewrittensynchronouslyto
the underlying storage device.
•
"rws"
informs the constructor to create and open a new file when it doesn't
exist for reading and writing, or open an existing file for reading and writing.
Furthermore,eachupdatetothefile'scontentormetadatamustbewrittensyn-
chronously to the underlying storage device.
Note
Afile's
metadata
isdataaboutthefileandnotactualfilecontents.Examples
of metadata include the file's length and the time the file was last modified.
The
"rwd"
and
"rws"
modesensurethananywritestoafilelocatedonalocalstor-
agedevicearewrittentothedevice,whichguaranteesthatcriticaldataisn'tlostwhen
the operating system crashes. No guarantee is made when the file doesn't reside on a
local device.