Read-Only Buffers

Buffers can be read-only. For example, a buffer that's backed by a file on a CD-ROM would be read-only. Buffers might also be read-only if they're memory mapped to a file you don't have write permission for, or to the input buffer on a network card. A CharBuffer that wraps a CharSequence is read-only. If you aren't sure whether you can write to a buffer, you can invoke isReadOnly( ) before attempting to do so:

public abstract boolean isReadOnly( )

Any attempt to store data into a read-only buffer throws a ReadOnlyBufferException. This is a runtime exception.

You can create a read-only buffer using the asReadOnly( ) method:

public abstract ByteBuffer asReadOnlyBuffer( )

As usual, there are variants of this for all the different types of buffers that differ only in return type. For example, this is DoubleBuffer's asReadOnly( ) method:

public abstract DoubleBuffer asReadOnlyBuffer( )

This is essentially a view buffer of the same type that doesn't allow puts. Its mark, limit, position, capacity, and content are initially the same as those of the buffer from which it was created. However, from this point forward, the limit, mark, and position can change independently of the underlying buffer.

For buffers created in this way, "read-only" is a bit of a misnomer. While you cannot put into such a buffer, you can still put values into the original underlying buffer, and any changes made in that way will immediately be reflected in the overlaid read-only buffer.

There are no write-only buffers. All buffers can be read.

Java I/O
Java I/O
ISBN: 0596527500
EAN: 2147483647
Year: 2004
Pages: 244
Simiral book on Amazon © 2008-2017.
If you may any questions please contact us: