Java Reference
In-Depth Information
With the default number of primes to be generated, this example should produce the following output
following the file path:
File written is 3742 bytes.
NOTE
If you run the example to generate a given number of primes and then run
it again, the file is overwritten. Of course, if you generate fewer primes when you
rerun the program, the file size does not go down!
How It Works
I'm discussing only the body of the collection-based
for
loop that iterates over the elements in the
primes
array because that's the new functionality in the example. It is shown in bold.
You create the string first because you need to know its length so you can put the length in the buffer first.
You insert the length as type
double
in the view buffer,
doubleBuf
. You then put the string into
charBuf
as this buffer already maps to the position starting 8 bytes along from the start of
buf
. Next, you update
the position in
buf
to the element following the string. This enables you to map
longBuf
to the correct
position in the byte buffer. After creating the third view buffer,
longBuf
, you load the prime value. You
then update the position for
buf
to the byte following this value. This is the position as previously set
plus 8. Finally, you flip
buf
to set the position and limit for writing, and then write the contents of
buf
to
the file channel.
If you inspect the file with a plain text editor you should get an idea of what is in the file. You should be
able to see the Unicode strings separated by the binary values you have written to the file. Of course, the
binary value doesn't look particularly meaningful when viewed as characters.
This example writes the file one prime at a time, so it's not going to be very efficient. It would be better
to use a larger buffer and load it with multiple primes. Let's explore how you might do that with another
version of the program.
TRY IT OUT: Multiple Records in a Buffer
You load the byte buffer using three different view buffers repeatedly to put data for as many primes into
the buffer as you can. The basic idea is illustrated in
Figure 10-12
.