Java Reference
In-Depth Information
outputFile = new FileOutputStream(aFile);
} catch (FileNotFoundException e) {
e.printStackTrace(System.err);
System.exit(1);
}
FileChannel file = outputFile.getChannel();
final int BUFFERSIZE = 100; // Buffer size in bytes
ByteBuffer buf = ByteBuffer.allocate(BUFFERSIZE);
DoubleBuffer doubleBuf = buf.asDoubleBuffer();
buf.position(8);
CharBuffer charBuf = buf.asCharBuffer();
LongBuffer longBuf = null;
String primeStr = null;
for (int i = 0; i < primes.length; i++) {
primeStr = "prime = " + primes[i]; // 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(primes[i]); // Store the binary long value
buf.position(buf.position() + 8); // Set position after last value
buf.flip(); // and flip
try {
file.write(buf); // Write the buffer as before.
} catch (IOException e) {
e.printStackTrace(System.err);
System.exit(1);
}
buf.clear();
doubleBuf.clear();
charBuf.clear();
}
try {
System.out.println("File written is " + file.size() + " bytes.");
outputFile.close(); // Close the file and its channel
} catch (IOException e) {
e.printStackTrace(System.err);
System.exit(1);
}
System.exit(0);
}
}
This should produce the output:
File written is 3742 bytes.
Search WWH ::




Custom Search