Java Reference
In-Depth Information
buf.compact().limit(buf.position() +
(bytesLeft<buf.remaining() ? (int)bytesLeft : buf.remaining()));
return channel.read(buf);
}
}
This should result in the same output as the previous example.
How It Works
All the work is done in the indefinite while loop. Before the loop executes we create a direct buffer
with a capacity of 1024 bytes by calling the allocateDirect() method. A direct buffer will be faster
if we are reading a lot of data from a file as the data are transferred directly from the file to our buffer.
The code within the loop determines whether there are data in the buffer by calling the remaining()
method for the buffer object. The default settings for the buffer, with the position at zero and the limit at
the capacity, would suggest falsely that there are data in the buffer, so we set the position to the limit
initially so that the remaining() method will return zero.
Within the loop we first check whether there are sufficient bytes for the double value specifying the
string length. On the first iteration, this will definitely not be the case so the replenish() method will
be called to compact the buffer and read data from the file. We then flip the buffer and get the length of
the string. Of course, data in the file should be in groups of three items - string length, string, and
binary prime value - so the end-of-file will be detected when trying to obtain the first of these. In this
case we exit the loop by executing a break statement.
Next we get the string itself, after checking that there are sufficient bytes left in the buffer. We should never
find EOF so we put an assertion rather than a break if EOF is detected. Finally we obtain the binary prime
value in a similar way and output the group of three data items. The loop continues until all data have been
read and processed and EOF is recognized when we are looking for a string length value.
Copying Files
You probably don't need a file copy program as your operating system is bound to provide a facility for
this. However, it is a useful way of demonstrating how a file channel for any input file can transfer data
directly to a file channel for an output file without involving explicit buffers.
A file channel defines two methods for direct data transfer: :
Search WWH ::




Custom Search