Java Reference
In-Depth Information
Note
A
handle
isanidentifierthatJavapassestotheunderlyingplatformtoidentify,
inthiscase,aspecificopenfilewhenitrequiresthattheunderlyingplatformperforma
file operation.
FileDescriptor
is a small class that declares three
FileDescriptor
con-
stantsnamed
in
,
out
,and
err
.Theseconstantslet
System.in
,
System.out
,and
System.err
provideaccesstothestandardinput,standardoutput,andstandarderror
streams.
FileDescriptor
also declares a pair of methods:
•
void sync()
tells the underlying platform to
flush
(empty) the contents of
theopenfile'soutputbufferstotheirassociatedlocaldiskdevice.
sync()
re-
turns after all modified data and attributes have been written to the relevant
device. It throws
java.io.SyncFailedException
when the buffers
cannotbeflushed,orbecausetheplatformcannotguaranteethatallthebuffers
have been synchronized with physical media.
•
boolean valid()
determines whether or not this file descriptor object is
valid. It returns true when the file descriptor object represents an open file or
other active I/O connection; otherwise, it returns false.
Datathatiswrittentoanopenfileendsupbeingstoredintheunderlyingplatform's
outputbuffers.Whenthebuffersfilltocapacity,theplatformemptiesthemtothedisk.
Buffers improve performance because disk access is slow.
However,whenyouwrite data toarandom access file that'sbeen opened via mode
"rwd"
or
"rws"
,eachwriteoperation'sdataiswrittenstraighttothedisk.Asares-
ult,writeoperationsareslowerthanwhentherandomaccessfilewasopenedin
"rw"
mode.
Suppose you have a situation that combines writing data through the output buffers
andwritingdatadirectlytothedisk.Thefollowingexampleaddressesthishybridscen-
ario by opening the file in mode
"rw"
and selectively calling
FileDescriptor
's
sync()
method:
RandomAccessFile raf = new RandomAccessFile("employee.dat",
"rw");
FileDescriptor fd = raf.getFD();
// Perform a critical write operation.
raf.write(...);
// Synchronize with underlying disk by flushing platform's
output buffers to disk.