Java Reference
In-Depth Information
program.");
System.exit(1);
}
final int PRIMESREQUIRED = 10;
final int LONG_BYTES = 8;
long[] primes = new long[PRIMESREQUIRED];
int index = 0;
// Position for a prime
in the file
final long REPLACEMENT = 999999L;
// Replacement for a
selected prime
try {
FileChannel channel =
(FileChannel)(Files.newByteChannel(file, EnumSet.of(READ,
WRITE)));
final int PRIMECOUNT = (int)channel.size()/LONG_BYTES;
MappedByteBuffer buf = channel.map(
READ_WRITE, 0L,
channel.size()).load();
channel.close();
// Close the channel
for(int i = 0 ; i < PRIMESREQUIRED ; ++i) {
index = LONG_BYTES*(int)(PRIMECOUNT*Math.random());
primes[i] = buf.getLong(index);
buf.putLong(index, REPLACEMENT);
}
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();
}
}
}
MemoryMappedFile.java
This should output ten randomly selected primes, but some or all of the selections may turn out to be
99999L
, the value of
REPLACEMENT
, if you have not refreshed the contents of
primes_backup.bin
.
How It Works
The statements of interest are those that are different to the previous example.
You have an
import
statement for the
MappedByteBuffer
class name, and you import the static member
of the
MapMode
nested class to the
FileChannel
class that you use in the code.
You get the file channel with the following statement: