Java Reference
In-Depth Information
While we are here, let's cover two other methods that modify the limit and/or the position for a buffer.
The
clear()
method sets the limit to the capacity and the position to zero, so it restores these values
to the state they had when the buffer was created. This does
not
reset the data in the buffer though. The
contents are left unchanged. You call the
clear()
method when you want to reuse a buffer, either to
load new data into it, or to read data into it from a channel.The
rewind()
method simply resets the
position to zero, leaving the limit unchanged. This enables you to reread the data that is in the buffer.
Both of these methods are defined in the base class,
Buffer
, and both return a reference to the buffer
of type
Buffer
so you can chain these operations with others that are defined in the
Buffer
class.
Writing To a File
To start with, we will be using the simplest
write()
method for a file channel that writes the data
contained in a single
ByteBuffer
object to a file. The number of bytes written to the file is determined
by the buffer's position and limit when the
write()
method executes. Bytes will be written starting
with the byte at the buffer's current position. The number of bytes written is
limit-position
, which is the
number returned by the
remaining()
method for the buffer object. The
write()
method returns the
number of bytes written as a value type
int
.
A channel
write()
operation can throw any of five different exceptions:
Exception
Description
NonWritableChannelException
Thrown if the channel was not opened for
writing.
ClosedChannelException
Thrown if the channel is closed. Calling the
close()
method for the file channel will close
the channel, as will calling the
close()
method
for the file stream.
AsynchronousCloseException
Thrown if another thread closes the channel
while the write operation is in progress.
ClosedByInterruptException
Thrown if another thread interrupts the current
thread while the write operation is in progress.
IOException
Thrown if some other I/O error occurs.
The first of these is a subclass of
RuntimeException
, so you do not have to catch this exception. The
other four are subclasses of
IOException
, which must be caught, so the
write()
method call must
be in a
try
block. If you want to react specifically to one or other of these last four exceptions, you will
need to add a
catch
block for that specific type. Otherwise you can just include a single
catch
block
for type
IOException
to catch all four types of exception. For instance if you have set up a
ByteBuffer
,
buf
, ready to be written, you might code the write operation like this:
File aFile = new File("C:/Beg Java Stuff/myFile.text");
// Place to store an output stream reference
FileOutputStream outputFile = null;