Java Reference
In-Depth Information
data began. You have to either fix the length of the string so you know how many bytes are characters when
you read the file, or you must provide data in the file that specifies the length of the string. Let's therefore
choose to write the data corresponding to each prime as three successive data items:
1. A count of the length of the string as binary value (it would sensibly be an integer type, but you'll
make it type double because you need the practice).
2. The string representation of the prime value "prime = nnn" , where obviously the number of digits
3. The prime as a binary value of type long .
The basic prime calculation does not change at all, so you need only update the shaded method in the
previous example that writes the file.
The basic strategy is to create a byte buffer and then create a series of view buffers that map the three
different kinds of data into it. A simple approach would be to write the data for one prime at a time, so let's
try that first. Setting up the channel is the same, but it is better to change the file extension to .txt so you
can look at it as a text file.
Path file = createFilePath("Beginning Java Stuff", "primes.txt");
Changing the file extension to .txt also differentiates it from the original binary file that you wrote with
the previous version so you retain both. You will use of both files when you are looking into file read oper-
ations in the next chapter, so don't delete them.
The byte buffer has to be large enough to hold the double value that counts the characters in the string,
the string itself, plus the long value for the prime. The original byte buffer with 100 bytes capacity is plenty
big enough so let's go with that. You need to create three view buffers from the byte buffer, one that holds
the double value for the count, one for the string, and one for the binary prime value, but you have a prob-
lem, which is illustrated in Figure 10-11 .
FIGURE 10-11
Because the length of the string depends on the number of decimal digits in the value of each prime, you
don't know where it ends. This implies you can't map the last buffer, longBuf , to a fixed position in the byte
buffer, buf . You are going to have to set this buffer up dynamically inside the file-writing loop after you
figure out how long the string for the prime is. You can set up the first two view buffers outside the loop,
DoubleBuffer doubleBuf = buf.asDoubleBuffer();
Search WWH ::

Custom Search