Java Reference
In-Depth Information
// 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) {
final int BUFFERSIZE = 100; // Byte buffer size
try (WritableByteChannel channel = Files.newByteChannel(
file, EnumSet.of(WRITE,
CREATE))) {
ByteBuffer buf = ByteBuffer.allocate(BUFFERSIZE);
DoubleBuffer doubleBuf = buf.asDoubleBuffer();
buf.position(8);
CharBuffer charBuf = buf.asCharBuffer();
LongBuffer longBuf = null;
String primeStr = null;
for (long prime : primes) {
primeStr = "prime = " + prime;
// Create the
string
doubleBuf.put(0,(double)primeStr.length()); // Store the
string length
charBuf.put(primeStr);
// Store the
string
buf.position(2*charBuf.position() + 8);
// Position for
3rd buffer
longBuf = buf.asLongBuffer();
// Create the
buffer
longBuf.put(prime);
// Store the binary
long value
buf.position(buf.position() + 8);
// Set position after
last value
buf.flip();
// and flip
channel.write(buf);
// Write the buffer as
before
buf.clear();
doubleBuf.clear();
charBuf.clear();
}
System.out.println("File written is " +
((FileChannel)channel).size() + "
bytes.");
} catch (IOException e) {
e.printStackTrace();
}
}
}
PrimesToFile2.java
Search WWH ::




Custom Search