Java Reference
In-Depth Information
StringBuffer str = null;
for(int i = 0 ; i<PRIMESREQUIRED ; i++) {
str = new StringBuffer(" ").append(primes[i]);
System.out.print((i%5 == 0 ? "\n" : "") + str.substring(str.length()-12,
str.length()));
}
ioFile.close(); // Close the file and the channel
} catch(IOException e) {
e.printStackTrace(System.err);
System.exit(1);
}
System.exit(0);
}
}
This should output ten randomly selected primes but some or all of the selections may turn out to be
999999L, the value of REPLACEMENT.
How It Works
The statements of interest are those that are shaded. The others we have seen before. We create a
RandomAccessFile object with " rw " access to the file:
ioFile = new RandomAccessFile(aFile,"rw");
This statement executes in a try block since it can throw a FileNotFoundException . We get the file
channel for ioFile with the statement:
FileChannel ioChannel = ioFile.getChannel();
We then create and load a MappedByteBuffer object with the statement:
MappedByteBuffer buf =
ioChannel.map(ioChannel.MAP _ RW, 0L, ioChannel.size()).load();
The buffer is created with the mode that permits the buffer to be accessed or modified and
modifications will be written to the file. The buffer maps to the entire file since we specify the start file
position as zero and the length mapped as the length of the file. The map() method returns a reference
to the MappedByteBuffer object that is created and we use this to call its load() method to request
that the contents of the file are loaded into memory immediately. The load() method also returns the
same buffer reference that is stored in buf .
Note that it is not essential to call the load method before you access the data in the buffer. If the data is
not available when you try to access it through the MappedByteBuffer object, it will be loaded for
you. Try running the example with the call to load() removed. It should work the same as before.
Inside the for loop, we retrieve a value from the buffer at a random position, index :
primes[i] = buf.getLong(index);
Search WWH ::




Custom Search