Java Reference
In-Depth Information
try {
// Create the stream opened to write
outputFile = new FileOutputStream(aFile);
} catch (FileNotFoundException e) {
e.printStackTrace(System.err);
}
// Get the channel for the file
FileChannel outputChannel = outputFile.getChannel();
try {
outputChannel.write(buf);
} catch (IOException e) {
e.printStackTrace(System.err);
}
A write() method for a channel will only return when the write operation is complete, but this does
not guarantee that the data has actually been written to the file. Some of the data may still reside in the
native I/O buffers. If the data you are writing is critical and you want to minimize the risk of losing it in
the event of a system crash, you can force all outstanding output operations to a file that were
previously executed by the channel to be completed by calling the force() method for the
FileChannel object like this:
try {
outputChannel.force();
} catch (IOException e) {
e.printStackTrace(System.err);
}
The force() method will throw a ClosedChannelException if the channel is closed, or an
IOException if some other I/O error occurs. Note that the force() method only guarantees that all
data will be written for a local storage device.
Only one write operation can be in progress for a given file channel at any time. If you call write()
while a write() operation initiated by another thread is in progress, your call to the write() method
will block until the write that is in progress has been completed.
File Position
The position of a file is the index position of where the next byte is to be read or written. The first byte
in a file is at position zero so the value for a file's position is the offset of the next byte from the
beginning. Don't mix this up with a buffer's position that we discussed earlier - the two are quite
independent, but of course, they are connected. When you write a buffer to a file using the write()
method we discussed in the previous section, the byte in the buffer at the buffer's current position will
be written to the file at its current position:
Search WWH ::




Custom Search