Java Reference
In-Depth Information
NIO applications. They are certainly the only methods not already covered that will
be needed for implementation of the chat server in Exercise 3.6 at the end of this
chapter. In fact, of the six new methods mentioned below, only four are NIO meth-
ods. The other two are methods of the
String
class. In all the examples within this
section,
buffer
is assumed to be a pre-declared
ByteBuffer
.
Though methods
read
and
write
are the usual methods for transferring data to
and from buffers, there are occasions when it is necessary to implement I/O at the
byte level. This is particularly so when the programmer wishes to place particular
values into a buffer or to remove all or part of the data from the buffer in order to
carry out further processing on that data (possibly prior to re-writing the processed
data back to the buffer). The methods to read and write a single byte from/to a buffer
are
get
and
put
respectively.
Examples
byte oneByte = buffer.get();
buffer.put(anotherByte);
As was stated in the previous sub-section, each
ByteBuffer
has at its heart an
array for storing the data that is to be read from or written to a particular channel.
Sometimes, it is desirable to access the contents of this array directly. Method
array
of class
ByteBuffer
allows us to do just this by returning the array of bytes holding
the data. For example:
byte[] bufferArray = buffer.array();
If the data that is being transferred is of type
String
, then we may wish to convert
this array of bytes into a
String
. This may be achieved by using an overloaded form
of the
String
constructor that has this form:
String(<byteArray>, <offset>, <numBytes>)
In the above signature, 'offset' is an integer specifying the byte number at which
to start in the array of bytes, while 'numBytes' specifi es the number of bytes from
the array that are to be used (counting from position 'offset'). Obviously, we need
to know how many bytes of data there are in the array. The reader's fi rst inclination
may be to assume that this can be derived from the array's
length
property. However,
this will not work, since it will simply show the size that was allocated to the
ByteBuffer
by the programmer, not the number of bytes that have been used. In
order to determine how many data bytes have been written to the buffer, one must
use the
ByteBuffer
's
position
method
following the latest writing to the buffer
(i.e., before the buffer is 'fl ipped' for reading).
Example
int numBytes = buffer.position();
byte[] bufferArray = buffer.array();
String dataString =
new String(bufferArray, 0, numBytes);
Search WWH ::
Custom Search