Java Reference
In-Depth Information
How It Works
We only need to discuss the loop. We first create the string because we need to know its length so we
can put that in the buffer first. We insert the length as type double in the view buffer, doubleBuf . We
can then put the string into charBuf as this buffer already maps to the elements 8 along from the start
of buf . Next, we update the position in buf to the element following the string. This will allow us to
map longBuf to the byte buffer correctly. After creating the third view buffer, longBuf , we load the
prime value. We then update the position for buf to the byte following this value. This will be the
position as previously set plus 8. Finally we flip buf to set the position and limit for writing, and then
the channel writes to the file.
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 we have written to the file.
This 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 see how we can do that.
Try It Out - Multiple Records in a Buffer
We will be loading the byte buffer using three different view buffers repeatedly to put as many primes
into the buffer as we can. The basic idea is illustrated below:
ByteBuffer
Double Buffer
CharBuffer
Long Buffer
Double Buffer
CharBuffer
Long Buffer
String Length
The String
Prime Value
String Length
The String
Prime Value
We will just show the new code that replaces the code in the previous example that allocates the buffers
and writes the file:
import java.io.*;
import java.nio.*;
import java.nio.channels.FileChannel;
public class PrimesToFile3 {
public static void main(String[] args) {
// Code as in the previous example...
final int BUFFERSIZE = 1024; // Buffer size in bytes - bigger!
ByteBuffer buf = ByteBuffer.allocate(BUFFERSIZE);
String primeStr = null;
int primesWritten = 0;
while (primesWritten < primes.length) {
while (primesWritten < primes.length) {
Search WWH ::




Custom Search