Java Reference
In-Depth Information
This creates a view buffer of type DoubleBuffer and calls its put() method to transfer the length of
the string to the buffer. We don't save the view buffer reference because we will need a different one on
the next iteration - one that maps to the position in the byte buffer following the data we are
transferring for the current prime.
The next statement increments the position of the byte buffer, by the number of bytes in the string
length value. We then execute the statement:
buf.position(buf.position()
+ 2 * buf.asCharBuffer().put(primeStr).position());
This statement is a little complicated so let's dissect it. The expression for the argument to the
position() method within the parentheses executes first. This calculates the new position for buf as
the current position, given by buf.position() , plus the value resulting from the expression:
2 * buf.asCharBuffer().put(primeStr).position()
The subexpression, buf.asCharBuffer() , creates a view buffer of type CharBuffer . The put()
method for this is called to transfer primeStr to the buffer, and this returns a reference to the
CharBuffer object. This is used to call its position() method that will return the position after
transferring the string, so multiplying this by 2 gives the number of bytes occupied by the string in buf .
Thus, the position for buf is updated to the point following the string.
The last step in the loop is to execute the statements:
buf.asLongBuffer().put(primes[primesWritten++]);
buf.position(buf.position() + 8);
The first statement here transfers the binary prime value to the buffer via a view buffer of type LongBuffer
and increments the count of the number of primes written to the file. The second statement updates the
position for buf to the next available byte. The inner while loop then continues with the next iteration to
load the data for the next prime into the buffer. This will continue until there is insufficient space for another
prime, whereupon the inner loop will end, and the buffer will be written to the file.
Gathering-Write Operations
We will look at one further file channel output capability before we try to read a file - the ability to
transfer data to a file from several buffers in sequence in a single write operation. This is called a
gathering-write operation. The advantage of this capability is that it avoids the necessity to copy
information into a single buffer before writing it to a file. A gathering-write operation is one side of what
are called scatter-gather I/O operations . We will look into the other side - the scattering-read
operation - in the next chapter.
Just to remind you, a file channel has two methods that can perform a gathering-write operation:
Search WWH ::




Custom Search