Java Reference
In-Depth Information
Since a String object is immutable, the buffer that results from this is read-only. Attempting to transfer
data into the buffer will result in an exception of type ReadOnlyBufferException being thrown.
Marking a Buffer
You use the mark property for a buffer to record a particular index position in the buffer, which you
want to be able to return to later. You can set the mark to the current position by calling the buffer
object's mark() method that is inherited from the Buffer class. For example:
buf.mark();
This method also returns a reference of type Buffer so you could chain it with the methods for setting
the limit and position:
buf.limit(512).position(256).mark();
This will set the mark to 256, the same as the position.
After a series of operations that alter the position, you can reset the buffer's position to the mark that
you have set by calling the reset() method that is inherited from the Buffer class:
buf.reset();
If you have not set the mark, or it has been discarded by an operation to set the limit or the position, the
reset() method will throw an exception of type InvalidMarkException . The mark for a view
buffer operates independently of the mark for the buffer from which it was created.
You probably won't need to mark a buffer most of the time. You would typically use it in a situation
where you are scanning some part of a buffer to determine what kind of data it contains, after reading a
file for instance. You could mark the point where you started the analysis, and then return to that point
by calling reset() for the buffer when you have figured out how to deal with the data.
Buffer Data Transfers
Of course, before you can use a channel to write the contents of a buffer to a file, you need to load the
buffer with the data. Methods for loading data into a buffer are referred to as put methods . Similarly,
when a channel has read data from a file into a buffer, you are likely to want to retrieve the data from
the buffer. In this case you use the buffer's get methods .
There are two kinds of operations that transfer data elements to or from a buffer. A relative put or get
operation transfers one or more elements starting at the buffer's current position. In this case the
position is automatically incremented by the number of elements transferred. In an absolute put or get
operation , you explicitly specify an index for the position in the buffer where the data transfer is to
begin. In this case the buffer's position will not be updated so it will remain at the index value it was
before the operation was executed.
Search WWH ::




Custom Search