Java Reference
In-Depth Information
getPrimes(primes); // Calculate the
primes
Path file = createFilePath(
"Beginning Java Stuff",
"GatheringWritePrimes.txt");
writePrimesFile(primes, file); // Write the file
}
// getPrimes() method as in the previous example...
// createFilePath() method as in the previous example...
// Write the array contents to file
private static void writePrimesFile(long[] primes, Path file) {
try (GatheringByteChannel channel =
(FileChannel)(Files.newByteChannel(file, EnumSet.of(WRITE,
CREATE)))){
ByteBuffer[] buffers = new ByteBuffer[3];
// Array of buffer
references
buffers[0] = ByteBuffer.allocate(8);
// To hold a double
value
buffers[2] = ByteBuffer.allocate(8);
// To hold a long
value
String primeStr = null;
for (long prime : primes) {
primeStr = "prime = " + prime;
buffers[0].putDouble((double) primeStr.length()).flip();
// Create the second buffer to accommodate the string
buffers[1] = ByteBuffer.allocate(primeStr.length());
buffers[1].put(primeStr.getBytes()).flip();
buffers[2].putLong(prime).flip();
channel.write(buffers);
buffers[0].clear();
buffers[2].clear();
}
System.out.println("File written is " +
((FileChannel)channel).size() + "
bytes.");
} catch (IOException e) {
e.printStackTrace();
}
}
}
GatheringWrite.java
When you execute this with the default of 100 primes generated, it should produce the following output
about the file size:
Search WWH ::




Custom Search