Java Reference
In-Depth Information
outputFile.close(); // Close the file and its channel
} catch (IOException e) {
e.printStackTrace(System.err);
System.exit(1);
}
System.out.println("File closed");
System.exit(0);
}
}
When you execute this, it should produce the output:
File written is 2671 bytes.
File closed
The length of the file is considerably less than before, since we are writing the string as bytes rather than
Unicode characters. The only part of the code that is different is shaded so we'll concentrate on that.
How It Works
We will be using three byte buffers: one for the string length, one for the string itself, and one for the
binary prime value:
// Array of buffer references
ByteBuffer[] buffers = new ByteBuffer[3];
We therefore create a ByteBuffer[] array with three elements to hold references to these. The
buffers holding the string length and the prime value are fixed in length so we are able to create those
straight away to hold 8 bytes each:
buffers[0] = ByteBuffer.allocate(8); // To hold a double value
buffers[2] = ByteBuffer.allocate(8); // To hold a long value
We have to create dynamically, the buffer to hold the string, inside the for loop that iterates over all
the prime values we have in the primes array.
After assembling the prime string, we transfer the length to the first buffer:
buffers[0].putDouble((double) primeStr.length()).flip();
Note that we flip the buffer in the same statement after the data value has been transferred, so it is set
up ready to be written to the file.
Next, we create the buffer to accommodate the string, load the byte array equivalent of the string and
flip the buffer:
buffers[1] = ByteBuffer.allocate(primeStr.length());
buffers[1].put(primeStr.getBytes()).flip();
Search WWH ::




Custom Search