Java Reference
In-Depth Information
LongBuffer longBuf = ((ByteBuffer)(buf.flip())).asLongBuffer();
primesRead = longBuf.remaining();
longBuf.get(primes,0, longBuf.remaining());
System.out.println();
for(int i = 0 ; i< primesRead ; i++)
System.out.print(" "+primes[i]);
buf.clear(); // Clear the buffer for the next read
}
The shaded lines reflect changes to the code in the original example. Now we always read the number
of values available in longBuf so we can't cause the BufferUnderflowException to be thrown.
A further possibility is to use a buffer large enough to hold all the primes in the file. We can work this
out from the value returned by the size() method for the channel - which is the length of the file in
bytes. We could do that like this:
final int PRIMECOUNT = (int)inChannel.size()/8;
Of course, you also must alter the for loop that outputs the primes so it doesn't attempt to put them all
on the same line. There is a hazard with this though if you don't know how large the file is. Unless your
PC is unusually replete with RAM, it could be inconvenient if the file contains the first billion primes. It
might be as well to put an assertion to protect against an excess of primes:
assert inChannel.size()<=100000;
final int PRIMECOUNT = (int)inChannel.size()/8;
Now the program will not proceed if there are more than 100,000 primes in the file. Don't forget, to
compile a program with assertions you must specify the -source 1.4 options, and when you execute
the program you need to specify the -enableassertions option.
Making the Output Pretty
One final point before we leave this example - the output is irritating. Why don't the columns line up?
Well they should and could, but it's a bit more code that would clutter up the example. However,
suppose we want to output the primes six to a line, left justified in a field width of 12. Here's one way
we could do that:
StringBuffer str = null;
for(int i = 0 ; i< primesRead ; i++) {
str = new StringBuffer(" ").append(primes[i]);
System.out.print((i%6 == 0 ? "\n" : "") + str.substring(str.length()-12,
str.length()));
}
This replaces the loop in the original code. On the first and every sixth prime output we start a new line by
outputting " \n " as the first character in the argument to the print() method. We create a StringBuffer
object, which contains 11 spaces, and append the String representation of the prime value to it. We then
just output the string consisting of the last 12 characters in the StringBuffer object.
Search WWH ::




Custom Search