Java Reference
In-Depth Information
final int PRIMESREQUIRED = 10;
final int LONG_BYTES = 8;
ByteBuffer buf = ByteBuffer.allocate(LONG_BYTES);
long[] primes = new long[PRIMESREQUIRED];
int index = 0;
// Position for a
prime in the file
final long REPLACEMENT = 99999L;
// Replacement for a
selected prime
try (SeekableByteChannel channel =
Files.newByteChannel(file, EnumSet.of(READ,
WRITE))){
final int PRIMECOUNT = (int)channel.size()/8;
System.out.println("Prime count = "+PRIMECOUNT);
for(int i = 0 ; i < PRIMESREQUIRED ; ++i) {
index = LONG_BYTES*(int)(PRIMECOUNT*Math.random());
channel.position(index).read(buf);
// Read at a random
position
buf.flip();
// Flip the buffer
primes[i] = buf.getLong();
// Extract the prime
buf.flip();
// Flip to ready for
insertion
buf.putLong(REPLACEMENT);
// Replacement into
buffer
buf.flip();
// Flip ready to write
channel.position(index).write(buf);
// Write the
replacement to file
buf.clear();
// Reset ready for
next read
}
int count = 0;
// Count of primes
written
for(long prime : primes) {
System.out.printf("%12d", prime);
if(++count%5 == 0) {
System.out.println();
}
}
} catch(IOException e) {
e.printStackTrace();
}
}
}
RandomReadWrite.java
This outputs from the file a set of ten random prime selections that have been overwritten. If you want
to verify that you have indeed overwritten these values in the file, you can run the ReadPrimes example
that you wrote earlier in this chapter with the file name as "primes_backup.bin" .
Search WWH ::




Custom Search